1. 程式人生 > >spring boot 整合WebService Cxf簡單例項(soap)

spring boot 整合WebService Cxf簡單例項(soap)

這裡是一個簡單的例子

服務端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>
這裡只依賴可一個Cxf元件,服務端配置類如下:
@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();
	}

}
這裡@WebService註解標明是一個服務類,targetNamespace指釋出的名稱空間,介面和實現類必須一致要不然會報錯,如果不指定預設是當前包路徑;endpointInterface指釋出的哪個類的方法,這裡指定介面的路徑,表示對外發布介面中的方法,如果不指定預設釋出當前類的所有方法(注意實現類比介面方法多的情況);@WebMethod修飾一個釋出的方法,可以改方法名或者排除不釋出;
這裡傳遞的是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=男]]