CXF service的幾種使用方法

以下以服務端和客戶端列舉幾種CXF的常用方法:
服務器端:

 

方法一:使用Endpoint.publish進行發佈,這種方式不需要其他的額外的包,也不需要進行配置文件的書寫,可以用於底層屬jdbc型的應用程序,其中第一個參數爲訪問時需要調用的功用地址,第二個參數爲要發佈的接口的實現類(此種方法非Cxf方式)
Endpoint endpoint =
 Endpoint.publish("http://localhost:8080/helloService",new HelloServiceImpl());
System.out.println("WS發佈成功!");
  

 

方法二:用CXF的JaxWsServerFactoryBean類進行發佈,使用這種方式發佈,需要導入CXF相關的jar包,但是不需要進行相關配置文件的書寫,其中address爲發佈的地址,serviceClass爲接口類

 

 

HelloServiceImpl impl = new HelloServiceImpl();
JaxWsServerFactoryBean factoryBean = new JaxWsServerFactoryBean();
factoryBean.setAddress("http://localhost:8080/WSCXF/helloService");//發佈地址
factoryBean.setServiceClass(IHelloService.class);//接口類
factoryBean.setServiceBean(impl);//發佈接口的實現類的實例
factoryBean.create();
System.out.println("WS發佈成功!");
 

 

 

方法三:使用配置式的,該方法既需要導入CXF的相關jar包,也需要進行配置文件的書寫,這種方法適用於與spring整合的應用中,因爲可以將bean託管給spring,也就可以隨心所欲的使用spring中配置的bean了,以下是application-server.xml文件的配置信息

 

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
	http://cxf.apache.org/jaxws
	http://cxf.apache.org/schemas/jaxws.xsd">

    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

    <!--cxf配置信息-->
    <bean id="helloServiceBean" class="org.cxf.service.HelloServiceImpl"/>
    <jaxws:endpoint id="helloService" implementor="#helloServiceBean" address="/hello">
    </jaxws:endpoint>

</beans>

 

 

 

客戶端:

 

方法一:使用CXF中 JaxWsProxyFactoryBean客戶端代理工廠調用web服務,這種方法需要導入cxf相關的jar包,由於需要顯式調用暴露方法的接口來生成一個實例,因此該方法適用於服務器端與客戶端處於同一個應用的相同服務下的應用程序

 

JaxWsProxyFactoryBean soapFactoryBean = new JaxWsProxyFactoryBean();
soapFactoryBean.setAddress("http:// localhost:8080/helloService");
soapFactoryBean.setServiceClass(IHelloService.class);
Object o = soapFactoryBean.create();
IHelloService helloService = (IHelloService)o;
helloService.sayHello();//sayHello()爲暴露的接口中的一個方法;

 

 

方法二:這種方法需要導入相關CXF的jar包,該方法的好處是隻需要知道相關的暴露接口中的方法名,既可以隱式調用,適合於發佈的服務器和調用的客戶端不處於同一應用,同一服務下的應用程序,注意
http://localhost:8080/WSCXF/helloService   //爲暴露的接口的名稱
?wsdl 必須要添加,這個是接口解析成的xml文件

 

JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client client = 
   dcf.createClient("http://localhost:8080/WSCXF/helloService?wsdl");

//sayHello爲接口中定義的方法名稱張三爲傳遞的參數返回一個Object數組
Object[] objects=client.invoke("sayHello", "張三");

//輸出調用結果
System.out.println(objects[0].toString());

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章