spring boot 整合WebService Cxf簡單例項(soap)
阿新 • • 發佈:2019-01-24
這裡是一個簡單的例子
服務端pom檔案如下<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cxf</groupId> <artifactId>cxf</artifactId> <version>0.0.1-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-spring-boot-starter-jaxws</artifactId> <version>3.1.12</version> </dependency> </dependencies> </project>
@Configuration public class TestConfig { //這裡有預設值,如果不配置預設是/services/* @Bean public ServletRegistrationBean dispatcherServlet() { return new ServletRegistrationBean(new CXFServlet(), "/test/*"); } @Bean(name = Bus.DEFAULT_BUS_ID) public SpringBus springBus() { return new SpringBus(); } @Bean public CxfService cxfService() { return new CxfServiceImpl(); } @Bean public Endpoint endpoint() { EndpointImpl endpoint = new EndpointImpl(springBus(), cxfService()); endpoint.publish("/user"); return endpoint; } }
服務介面類如下
@WebService(targetNamespace="http://cxf.cgj")
public interface CxfService {
@WebMethod(operationName="sayHello")
String sayHello(@WebParam(name="User") User user);
}
服務介面實現類如下@WebService(targetNamespace="http://cxf.cgj",endpointInterface="cgj.cxf.CxfService") public class CxfServiceImpl implements CxfService { @Override public String sayHello(User user) { return "hello "+ user.toString(); } }
這裡傳遞的是javaBean型別,這裡還有一點,必須保證服務端的User與客戶端的User在同一包下,不然會報錯。
客戶端pom與服務端一致,客戶端程式碼如下
public static void main(String[] args) throws Exception {
JaxWsDynamicClientFactory dcf =JaxWsDynamicClientFactory.newInstance();
org.apache.cxf.endpoint.Client client =dcf.createClient("http://localhost:8080/test/user?wsdl");
User user=new User();
Body body=new Body();
body.setGender("男");
user.setBody(body);
Object[] objects=client.invoke("sayHello",user);
System.out.println("*****"+objects[0].toString());
}
輸出結果如下hello User [sysHead=null, body=Body [name=null, gender=男]]