最近接手了一个项目,要实现WebService接口调用的功能。java开发WebService的框架主要包括axis2和CXF,CXF属于轻量级WebService的框架,支持spring集成;axis2相较来说有点笨重,和spring配合使用不太友好,所以此次选择CXF进行开发。
1. 服务端
1.1 引入依赖
创建SpringBoot项目,引入CXF所需依赖,pom文件如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.5</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- CXF webservice -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxws</artifactId>
<version>3.4.3</version>
<exclusions>
<exclusion>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.4.3</version>
</dependency>
<!-- CXF webservice -->
</dependencies>
1.2 CXF配置
package com.cn.cxf.config;
import com.cn.cxf.service.TSAService;
import org.apache.cxf.Bus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.xml.ws.Endpoint;
@Configuration
public class WebServiceConfig {
@Autowired
private TSAService service;
@Autowired
private Bus bus;
/**
* 设置Webservice接口访问前缀
* @return
*/
@Bean(name = "cxfServlet")
public ServletRegistrationBean dispatcherServlet(){
return new ServletRegistrationBean(new CXFServlet(),"/cxf/*");
}
/**
* 将Webservice接口进行暴露
* 访问路径:ip+端口+/cxf+/webservice
* @return
*/
@Bean
public Endpoint userEndpoint(){
EndpointImpl endpoint=new EndpointImpl(bus,service);
endpoint.publish("/webservice");
return endpoint;
}
}