引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.1.6</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>3.1.6</version>
</dependency>
写接口
@WebService
public interface WebServiceDemoService {
@WebMethod
String hello(@WebParam(name = "name")String name);
}
接口实现
@Service
@WebService(serviceName = "WebServiceDemoService", // 与接口中指定的name一致
targetNamespace = "http://webservice.business.mixpay.com", // 与接口中的命名空间一致,一般是接口的包名倒
endpointInterface = "com.mixpay.business.webservice.WebServiceDemoService" // 接口地址
)
public class WebServiceDemoServiceImpl implements WebServiceDemoService {
@Override
public String hello(String name) {
return "hello"+name;
}
}
新建webservice配置类WebServiceConfig
@Configuration
public class WebServiceConfig {
@Autowired
private WebServiceDemoService webServiceDemoService;
/**
* 注入servlet bean name不能dispatcherServlet 否则会覆盖dispatcherServlet
* @return
*/
@Bean(name = "cxfServlet")
public ServletRegistrationBean cxfServlet() {
return new ServletRegistrationBean(new CXFServlet(),"/webservice/*");
}
@Bean(name = Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
return new SpringBus();
}
/**
* 注册WebServiceDemoService接口到webservice服务
* @return
*/
@Bean(name = "WebServiceDemoEndpoint")
public Endpoint sweptPayEndpoint() {
EndpointImpl endpoint = new EndpointImpl(springBus(), webServiceDemoService);
endpoint.publish("/webservice");
return endpoint;
}
}
启动项目后,游览器访问 http://localhost:端口/CXFServlet注册地址 本例访问http://localhost:8080/webservice
接口调用
/**
* 1.代理类工厂的方式,需要拿到对方的接口地址
*/
public static void main1() {
try {
// 接口地址
String address = "你的接口http://localhost:8080/webservice";
// 代理工厂
JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
// 设置代理地址
jaxWsProxyFactoryBean.setAddress(address);
// 设置接口类型
jaxWsProxyFactoryBean.setServiceClass(UserService.class);
// 创建一个代理接口实现
UserService us = (UserService) jaxWsProxyFactoryBean.create();
// 数据准备
String name= "maple";
// 调用代理接口的方法调用并返回结果
String result = us.getUserName(name);
System.out.println("返回结果:" + result);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 2:动态调用
*/
public static void main2() {
// 创建动态客户端
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = dcf.createClient("你的接口 http://localhost:8080/webservice");
// 需要密码的情况需要加上用户名和密码
// client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME, PASS_WORD));
Object[] objects = new Object[0];
try {
// invoke("方法名",参数1,参数2,参数3....);
objects = client.invoke("getUserName", "maple");
System.out.println("返回数据:" + objects[0]);
} catch (java.lang.Exception e) {
e.printStackTrace();
}
}