SpringBoot中整合使用WebService

我使用的SpringBoot的版本为 2.0.3.RELEASE

首先pom.xml文件中加入WebService的相关依赖:


      org.apache.cxf
      cxf-spring-boot-starter-jaxws
      3.2.5

WebService接口:

@javax.jws.WebService(serviceName = "WSServer", // 服务名称
        targetNamespace = "http://service.webservice.com/"// 一般是接口的包名倒序
)
public interface WebService {
    @WebMethod
    @WebResult(name = "String", targetNamespace = "")
    public String testWS(@WebParam(name = "msg") String msg);

}

实现类:

@javax.jws.WebService(serviceName = "WSServer", // 与接口中指定的name一致
        targetNamespace = "http://service.webservice.com/"// 与接口中的命名空间一致,一般是接口的包名倒序
)
@Component
public class WebServiceImpl implements WebService {

       @Override
       public String testWS(String msg){
             return msg;
       }

}

发布webservice服务

import com.webservice.service.WebService;
import com.webservice.service.WebServiceImpl;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.xml.ws.Endpoint;

@Configuration
public class CxfConfig {

    @SuppressWarnings("all")
    @Bean(name = "cxfServlet")
    public ServletRegistrationBean cxfServlet() {
        //创建服务并指定服务名称
        return new ServletRegistrationBean(new CXFServlet(),"/webservice/*");
    }



    @Bean(name = Bus.DEFAULT_BUS_ID)
    public SpringBus springBus() {

        return new SpringBus();
    }


    @Bean
    public WebService webService(){

        return new WebServiceImpl();
    }

    /**
     * 注册WebServiceDemoService接口到webservice服务
     * @return
     */
    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(springBus(),webService());
        endpoint.publish("/webServiceImpl");
        return endpoint;
    }

}

启动服务,在浏览器输入服务ip:port/webservice   即可看到服务的WSDL地址等相关信息。

接下来使用CXF动态调用我们创建的服务:

        // 创建动态客户端
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient("http://192.168.4.100:8080/webservice/webServiceImpl?wsdl");
        // 需要密码的情况需要加上用户名和密码
         //client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME,PASS_WORD));
        Object[] objects = new Object[0];
        try {
            // invoke("方法名",参数1,参数2,参数3....);
            objects = client.invoke("testWS", "测试WS是否调用成功");
            System.out.println("返回数据======================:" + objects[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }

 调用成功控制台会打印出:

返回数据======================:测试WS是否调用成功

 

 

 

 

你可能感兴趣的:(WebService)