spring boot 整合cxf webservice

spring boot 整合 cxf webservice

创建spring boot工程,增加cxf的依赖

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

服务端

创建服务接口
@WebService(name = "CommonService", //服务民称
              targetNamespace = "http://bb.aa.com" //命名空间
)
public interface CommonService {

  @WebMethod
  @WebResult(name = "String", targetNamespace = "")
  public String sayHello(@WebParam(name = "userName") String name);
}
实现接口
@WebService(serviceName = "CommonService", // 与接口中指定的name一致
    targetNamespace = "http://bb.aa.com", // 与接口中的命名空间一致,一般是接口的包名倒
    endpointInterface = "com.aa.bb.CommonService"// 接口地址
)
@Component
public class CommonServiceImpl implements CommonService {

  @Override
  public String sayHello(String name) {
    return "Hello ," + name;
  }
}

配置config

@Configuration
public class CxfConfig {
  @Autowired
  private Bus bus;

  @Autowired
  CommonService commonService;

  @Bean
  public Endpoint endpoint() {
    EndpointImpl endpoint = new EndpointImpl(bus, commonService);
    endpoint.publish("/CommonService");
    return endpoint;
  }
}

启动服务 就可以通过 http://localhost:8080/services/CommonService?wsdl 访问到wsdl文件了。

客户端

public class CxfClient {

  public static void main(String[] args) {
    try {
      // 接口地址
      String address = "http://localhost:8080/services/CommonService";

      // 代理工厂
      JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
      // 设置代理地址
      jaxWsProxyFactoryBean.setAddress(address);
      // 设置接口类型
      jaxWsProxyFactoryBean.setServiceClass(CommonService.class);
      jaxWsProxyFactoryBean.getOutInterceptors().add(new CxfAuthInterceptor());
      // 创建一个代理接口实现
      CommonService commonService = (CommonService) jaxWsProxyFactoryBean.create();
      // 数据准备
      String name = "666";
      // 调用代理接口的方法调用并返回结果
      String result = commonService.sayHello(name);
      System.out.println("返回结果:" + result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

拦截设置权限

public class CxfAuthInterceptor extends AbstractPhaseInterceptor {

  public CxfAuthInterceptor() {
    //准备发送阶段
    super(Phase.PREPARE_SEND);
  }

  @Override
  public void handleMessage(SoapMessage soapMessage) throws Fault {
    List
headers = soapMessage.getHeaders(); Document doc = DOMUtils.createDocument(); Element auth = doc.createElement("auth"); Element name = doc.createElement("name"); name.setTextContent("hwj"); Element password = doc.createElement("password"); password.setTextContent("123456"); auth.appendChild(name); auth.appendChild(password); headers.add(new Header(new QName(""), auth)); } }

本文永久更新地址: http://www.leftso.com/blog/144.html

你可能感兴趣的:(spring boot 整合cxf webservice)