您的位置:首页 > 编程语言 > Java开发

在web项目中使用cxf开发webservice,包含spring支持

2015-07-24 17:59 691 查看
本文主要介绍了,如何使用cxf内置的例子,学会开发webserivce,在web项目中使用,且包含spring支持。

webserivce的开发可以使用cxf或者axis,好像还有httpclient等等。以前也多次研究过,上网搜过很多别人的例子来看,写过代码下来,但没有总结过,少废话,上干货。

1. 到cxf的官网下载jar包。我用的是以前下载下来的apache-cxf-2.7.6.zip,并非最新版本。下载完成后,解压后,目录结构如下左图:

打开其中的samples文件夹,其内包含了很多例子的代码,找到我们要使用的例子java_first_spring_support,导入到Myeclipse中。



2. 导入之后,Maven下载完项目依赖的jar包后,我们可以看到,项目里面已经写好web.xml文件,cxf-servlet.xml文件和client-beans.xml文件。client-beans.xml文件,是客户端调用时要用到的。ws主要加载的是cxf-servlet.xml文件。为了项目启动时加载它,修改已经写好的web.xml文件内容,在其中加入以下代码:

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/cxf-servlet.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


注意,cxf-servlet.xml文件原来是在WEB-INF目录下的,写法/WEB-INF/classes/cxf-servlet.xml要求项目编译完成后,cxf-servlet.xml文件要在classes下面找得到,

所以,要把该文件配置在了classpath下面,如下图:



3. 完成相应的修改和配置后,启动项目,如控制台不报错,可以看到相应webservice创建的信息,如下:

2015-7-24 17:56:16 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@19a8739b: defining beans [cxf,org.apache.cxf.bus.spring.BusWiringBeanFactoryPostProcessor,org.apache.cxf.bus.spring.Jsr250BeanPostProcessor,org.apache.cxf.bus.spring.BusExtensionPostProcessor,helloWorld]; root of factory hierarchy
2015-7-24 17:56:17 org.apache.cxf.service.factory.ReflectionServiceFactoryBean buildServiceFromClass
信息: Creating Service {http://service.spring.demo/}HelloWorldImplService from class demo.spring.service.HelloWorld
2015-7-24 17:56:18 org.apache.cxf.endpoint.ServerImpl initDestination
信息: Setting the server's publish address to be /HelloWorld
2015-7-24 17:56:18 org.springframework.web.context.ContextLoader initWebApplicationContext
信息: Root WebApplicationContext: initialization completed in 2671 ms

4. 客户端调用。项目中包含了调用的测试代码,无须我们手动再编写,直接运行Client.java即可。

 值得注意的是,Client.java并不直接包含客户端调用逻辑的代码,而是通过调用一个cxf的工厂类,显然逻辑是在该工厂类内定义的,这个我们不必关心,只负责调用即可。

但,工厂类的一个属性address的值要修改一下,

即配置文件中client-beans.xml的<property name="address" value="http://localhost:9002/services/HelloWorld"/>的value,

本人的地址是,http://localhost:8080/JavaFirstSpringSupport/services/HelloWorld

至此,开发完成。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: