cxf与spring的整合
cxf与spring的整合:
一:服务端相关配置(配置好后启动tomocat就自动发布了接口,浏览器打开验证下)
1:导入cxf以及spring的相关jar包;
2:在web.xml中增加配置:
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <!--添加cxf配置文件--> 2 3 <context-param> 4 5 <param-name>contextConfigLocation</param-name> 6 7 <param-value>classpath:cxf.xml</param-value> 8 9 </context-param> 10 11 <!--添加监听器--> 12 13 <listener> 14 15 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 16 17 </listener> 18 19 <!--cxf配置--> 20 <servlet> 21 <servlet-name>cxfServlet</servlet-name> 22 <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> 23 </servlet> 24 <!-- 访问路由配置--> 25 <servlet-mapping> 26 <servlet-name>cxfServlet</servlet-name> 27 <url-pattern>/ws/*</url-pattern> 28 </servlet-mapping>
3:cxf文件的配置:
注意:发布的接口和接口的具体实现都要贴上@WebService标签;
spring-cxf.xml 代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:jaxws="http://cxf.apache.org/jaxws" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"> 8 <!--引入源码中的配置文件--> 9 10 <!--访问地址: http://localhost:8080/ws/product --> 11 <jaxws:server id="inlineImplementor" serviceClass="com.floor.shop.ws.IProductService" 12 address="/product"> 13 <jaxws:serviceBean> 14 <bean class="com.floor.shop.ws.impl.ProductService"/> 15 </jaxws:serviceBean> 16 </jaxws:server> 17 18 19 </beans>
二:客户端的相关配置:
0.拷贝jar包
1.在cmd中运行wsdl2java "http://localhost:8080/ws/product?wsdl 生成客户端代码
2.在spring配置文件中配置客户信息
在客户端项目的src文件夹下运行dos命令:
wsdl2java +服务端提供的访问接口
2:客户端的 spring-cxf.xml 的配置:
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"> 6 7 <!-- 访问地址: http://localhost:8080/ws/product --> 8 <jaxws:client id="productService" serviceClass="com.floor.shop.ws.IProductService" 9 10 address="http://localhost:8081/ws/product"/> 11 12 </beans>
3:客户端中方法的调用:
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 ClassPathXmlApplicationContext cxt = 2 new ClassPathXmlApplicationContext("spring/cxf_Client.xml"); 3 4 IProductService productService = (IProductService)cxt.getBean("productService"); 5 User user = new User(); 6 user.setUserName("张无忌"); 7 String s = productService.buyProduct(user); 8 System.out.println("s="+s);