最近开发因需求要求须要提供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、测试客户端开发