最近開發因需求要求須要提供Web Service接口供外部調用,因爲以前沒有研究過該技術,故查閱資料研究了一番,因此寫下來記錄一下,方便後續使用。html
這個demo採用CXF框架進行開發,後續所提到的Web Service 均由WS所替代。java
1、CXF所使用的maven依賴,版本爲:web
<cxf.version>3.1.4</cxf.version>
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-core</artifactId> <version>${cxf.version}</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>${cxf.version}</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>${cxf.version}</version> </dependency>
2、建立WS接口spring
import javax.jws.WebMethod; import javax.jws.WebService; @WebService public interface LogServiceWS { @WebMethod TSLog getLogById(String id); }
3、實現類apache
@WebService public class LogServiceWSImpl implements LogServiceWS { @Autowired private SystemService systemService; public LogServiceWSImpl(){ System.out.println("LogServiceWSImpl 初始化了。。。。。。。"); } @Override public TSLog getLogById(String id) { return systemService.getEntity(TSLog.class, id); } }
切記,實現類和接口儘可能放在同一個包中,這樣能夠避免後續生成的WSDL文件有import標籤,致使解析麻煩,或者在實現類上配置接口具體位置來解決該問題。spring-mvc
4、接下來配置CXF的配置文件cxf-beans.xmlmvc
<?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:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"> <!-- Cxf WebService 服務端示例 --> <jaxws:endpoint id="userServiceWSImpl" implementor="com.svw.hrssc.webservice.ws.LogServiceWSImpl" address="/log/getLogById"/> </beans>
implementor:表示WS接口的實現類app
address:表示該接口的訪問地址框架
因爲使用的CXF爲3.0以上版本,因此不須要引入那三個配置文件frontend
<import resource="classpath:META-INF/cxf/cxf.xml"/> <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/> <import resource="classpath:META-INF/cxf/cxf-servlet.xml"/>
5、接下來配置web.xml將CXF加入到項目啓動容器中,項目啓動的時候發佈WS接口。
首先把cxf-beans.xml文件加入context-param中,項目啓動的時候加載CXF配置文件,發佈WS接口。
<context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:spring-mvc-aop.xml, classpath*:spring-mvc.xml, classpath*:cxf-beans.xml </param-value> </context-param>
而後配置org.apache.cxf.transport.servlet.CXFServlet 做用:過濾請求,將符合CXF的請求交給接口處理。
<!--過濾cxf請求--> <servlet> <servlet-name>cxf</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>cxf</servlet-name> <url-pattern>/ws/services/*</url-pattern> </servlet-mapping>
根據配置可知,當有 /ws/services/* 格式的請求都會被過濾,而後交給CXF來處理。
至此,CXF服務端開發完成,能夠啓動項目訪問:http://localhost:8080/sscmanage/ws/services/ 查看接口是否發佈完成。
點擊WSDL後面的連接,能夠看到CXF產生的WSDL協議。標準的WSDL協議包含以下6部分:
6、測試客戶端開發