這幾天在研究WebService,簡單的整理一下吧。
1. 搭建一個Spring Boot項目
1.1 pom.xml
添加cxf框架依賴
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxws</artifactId>
<version>3.4.0</version>
</dependency>
1.2 cxf配置文件
@Configuration
public class CxfConfig {
@Autowired
private Bus bus;
@Autowired
CommonService commonService;
/** JAX-WS **/
@Bean
public Endpoint endpoint() {
EndpointImpl endpoint = new EndpointImpl(bus, commonService);
//發佈地址
endpoint.publish("/CommonService");
return endpoint;
}
}
1.3 新建service提供服務接口
@WebService(name = "CommonService", // 暴露服務名稱
targetNamespace = "http://springbootwebservice.zhouzhaodong.xyz/"// 命名空間,一般是接口的包名倒序
)
public interface CommonService {
/**
* 暴露接口
* @param name
* @return
*/
@WebMethod
String sayHello(@WebParam(name = "userName") String name);
}
1.4 新建service實現類
@WebService(serviceName = "CommonService", // 與接口中指定的name一致
targetNamespace = "http://springbootwebservice.zhouzhaodong.xyz/", // 與接口中的命名空間一致,一般是接口的包名倒
endpointInterface = "xyz.zhouzhaodong.springbootwebservice.service.CommonService"// 接口地址
)
@Component
public class CommonServiceImpl implements CommonService {
@Override
public String sayHello(String name) {
return "HELLO" + name;
}
}
1.5 webservice客户端
該類提供兩種不同的方式來調用webservice服務:
1:代理工廠方式
2:動態調用webservice
public class CxfClient {
public static void main(String[] args) {
cl2();
}
/**
* 方式1.代理類工廠的方式,需要拿到對方的接口
*/
public static void cl1() {
try {
// 接口地址
String address = "http://localhost:8080/services/CommonService?wsdl";
// 代理工廠
JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
// 設置代理地址
jaxWsProxyFactoryBean.setAddress(address);
// 設置接口類型
jaxWsProxyFactoryBean.setServiceClass(CommonService.class);
// 創建一個代理接口實現
CommonService cs = (CommonService) jaxWsProxyFactoryBean.create();
// 數據準備
String userName = "Leftso";
// 調用代理接口的方法調用並返回結果
String result = cs.sayHello(userName);
System.out.println("返回結果:" + result);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 方式2.動態調用方式
*/
public static void cl2() {
// 創建動態客户端
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = dcf.createClient("http://localhost:8080/services/CommonService?wsdl");
// 需要密碼的情況需要加上用户名和密碼
// client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME, PASS_WORD));
Object[] objects;
try {
objects = client.invoke("sayHello", "1");
List<Object> objects1 = Arrays.asList(objects);
System.out.println(objects1.get(0));
} catch (java.lang.Exception e) {
e.printStackTrace();
}
}
}
2. 測試
記住用JDK8打開哦
直接修改main方法裏面的調用就可以了。
個人博客地址
http://www.zhouzhaodong.xyz
GitHub源碼地址
https://github.com/zhouzhaodo...