这几天在研究WebService,简单的整理一下吧。
添加cxf框架依赖java
<dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-spring-boot-starter-jaxws</artifactId> <version>3.4.0</version> </dependency>
@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; } }
@WebService(name = "CommonService", // 暴露服务名称 targetNamespace = "http://springbootwebservice.zhouzhaodong.xyz/"// 命名空间,通常是接口的包名倒序 ) public interface CommonService { /** * 暴露接口 * @param name * @return */ @WebMethod String sayHello(@WebParam(name = "userName") String name); }
@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; } }
该类提供两种不一样的方式来调用webservice服务:
1:代理工厂方式
2:动态调用webservicegit
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(); } } }
记住用JDK8打开哦
直接修改main方法里面的调用就能够了。github
http://www.zhouzhaodong.xyzweb