1. 程式人生 > >CXF webService 與 SpringMVC 整合要點

CXF webService 與 SpringMVC 整合要點

1.準備cxf的jar包

2.在web.xml中配置cxf-servlet.xml

 <!-- CXF和servlet整合  走一下原始碼就知道它會找cxf-servlet.xml檔案-->
  <servlet>
    <servlet-name>cxf</servlet-name>
      <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
    <init-param>
        <param-name
>
config-location</param-name> <param-value>classpath:cxf-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <!-- 訪問WSDL檔案的時候就需要訪問這個名字,通過它可以找到web服務 --> <servlet-name>cxf</servlet-name> <url-pattern>/webService/*</url-pattern
>
</servlet-mapping>

3.cxf-servlet.xml中配置 webServcie 的 spring-webService.xml的bean

<beans xmlns="http://www.springframework.org/schema/beans"

        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

        xmlns:jaxws="http://cxf.apache.org/jaxws"

        xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"
>
<import resource="classpath:META-INF/cxf/cxf.xml"/> <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/> <jaxws:endpoint implementor="#WeChatService" address="/weChat"/> <import resource="spring-webService.xml"/> </beans>

4.spring-webService.xml注入service屬性

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <bean id="WeChatService" class="com.webService.WeChatService"></bean>

</beans>

5.為com.webService.WeChatService添加註解

@WebService(serviceName="WeChatService")
public class WeChatService {
     public void function1(){
     .........
     }
}

6.用web伺服器,如tomcat釋出訪問

7.生成client檔案,如

wsimport -s D:\\workspaces\\MyEclipse\\ws1Client\\src  -p com.web.client.eeams -keep http://localhost:8080/ws/webService/weChat?wsdl

特別注意:CXF在做webServices複雜物件傳遞時,返回值的型別不要用介面型別。例如(List 應該換成ArrayList ,Map應該換成HashMap),還有就是ArrayList<HashMap<Sting,Object>>也是cxf無法解析的,他會報list canot cast to a hashMap 建議使用 List<包裝物件>來返回複雜型別。