這幾天在研究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