需求描述
目前主流系统都已经支持Restful API接口了,但难免也有老系统仍然需要用WebService接口。故考虑在项目中引入CXF框架来发布和调用WebService接口。
实现思路
- 在POM文件中引入CXF框架依赖
- 定义Webservice服务端接口类、实现类、配置类
- 模拟客户端调用Webservice服务端接口。
操作步骤
pom.xml引入cxf
<!-- springboot webservice 这段也可以尝试不加入 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<!-- cxf webservice -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxws</artifactId>
<version>3.2.14</version>
</dependency>
定义Webservice服务端接口和实现类
TestWebService为WebService接口类,代码参考
/**
* TestService<br>
*
* @author namelessmyth
* @version 1.0
* @date 2021/12/13/0013
*/
@WebService(name = "TestWebService", // 暴露服务名称
targetNamespace = "http://webservice.ruoyi.com/"// 命名空间,一般是接口的包名倒序
)
public interface TestWebService {
@WebMethod(operationName = "testMethod")
String testMethod(@WebParam(name = "json") String json);
}
TestWebServiceImpl实现类代码参考
/**
* TestWebServiceImpl<br>
*
* @author namelessmyth
* @version 1.0
* @date 2021/12/13/0013
*/
@Component
public class TestWebServiceImpl implements TestWebService {
public String testMethod(String json) {
return "hello world : " + json;
}
}
CXF配置类,用于将定义好的WebService对外发布出去,代码参考
/**
* cxf webservice 配置<br>
*
* @author namelessmyth
* @version 1.0
* @date 2021/12/13/0013
*/
@Configuration
public class CxfConfig {
@Autowired
Bus bus;
@Autowired
TestWebService testService;
@Bean
public Endpoint endpoint() {
EndpointImpl endpoint = new EndpointImpl(bus, testService);
endpoint.publish("/TestWebService");
return endpoint;
}
}
启动SpringBoot服务,控制台会打印Webservice地址部署成功日志。
INFO o.a.c.w.s.f.ReflectionServiceFactoryBean - [buildServiceFromClass,437] - Creating Service {http://impl.webservice.ruoyi.com/}TestWebServiceImplService from class com.ruoyi.webservice.TestWebService
浏览器访问wsdl地址
http://localhost/services/TestWebService?wsdl
正常的话,到这里应该能看到,Webservice接口中的所有方法,参考下图。
客户端调用
客户端调用Webservice接口有很多种调用方式。例如:CXF客户端代码调用,Hutool代码调用,SoapUI,postman等。下文将介绍使用CXF客户端代码调用。
新建客户端调用类,CxfClient,代码参考:
public class CxfClient {
public static void main(String[] args) {
try {
// 接口地址
String address = "http://localhost/services/TestWebService?wsdl";
// 代理工厂
JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
// 设置代理地址
jaxWsProxyFactoryBean.setAddress(address);
// 设置接口类型
jaxWsProxyFactoryBean.setServiceClass(TestWebService.class);
// 创建一个代理接口实现
TestWebService us = (TestWebService) jaxWsProxyFactoryBean.create();
// 数据准备
String name = "zhang";
// 调用代理接口的方法调用并返回结果
String result = us.testMethod(name);
System.out.println("返回结果:" + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
写好之后,在idea中直接启动,调用本地的服务端。调用结果如下:
Creating Service {http://webservice.ruoyi.com/}TestWebServiceService from class com.ruoyi.webservice.TestWebService
返回结果:hello world :zhang