首先引入apache.cxf包maven坐标
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxws</artifactId>
<version>3.3.4</version>
</dependency>
发布WebService接口
接口定义
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
/**
* WebService接口
*
* @author 向振华
* @date 2022/06/22 10:20
*/
@WebService(name = "xzhWebService", targetNamespace = "http://webservice.xzh.com")
public interface XzhWebService {
@WebMethod
String xzhMethod(@WebParam(name = "xmlContent", targetNamespace = "http://webservice.xzh.com") String xmlContent);
}
实现类
/**
* @author 向振华
* @date 2022/06/22 10:22
*/
public class XzhWebServiceImpl implements XzhWebService {
@Override
public String xzhMethod(String xmlContent) {
return "success → " + xmlContent;
}
}
配置
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.xml.ws.Endpoint;
/**
* WebService接口配置
*
* @author 向振华
* @date 2022/06/22 10:25
*/
@Configuration
public class WebServiceConfig {
@Bean
public ServletRegistrationBean registration() {
// 注册servlet bean组件,并在路径上添加/ws(不是必须)
return new ServletRegistrationBean(new CXFServlet(), "/ws/*");
}
@Bean(name = Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
return new SpringBus();
}
@Bean
public XzhWebService webService() {
return new XzhWebServiceImpl();
}
@Bean
public Endpoint endpoint() {
EndpointImpl endpoint = new EndpointImpl(springBus(), webService());
// 发布的服务地址
endpoint.publish("/xzh");
return endpoint;
}
}
调用WebService接口
调用实际是个http请求,但是参数外层需要包装一层xml,我这里直接采用hutool工具包直接调用:
public static void main(String[] args) {
// 发送请求
SoapClient client = SoapClient.create("http://localhost:8596/bop-oms/ws/xzh")
.setMethod("xzhMethod", "http://webservice.xzh.com")
.setParam("xmlContent", "hello world!");
String res = client.send(true);
System.out.println(res);
}
可以看到打印的res接口为:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns2:xzhMethodResponse xmlns:ns2="http://webservice.xzh.com">
<return>success → hello world!</return>
</ns2:xzhMethodResponse>
</soap:Body>
</soap:Envelope>
采用Postman调用验证也能得到相同结果: