CXF也是WebService的一個(gè)實(shí)現(xiàn)框架,而且跟spring整合的非常好吴攒。下面講一下cxf的主要實(shí)現(xiàn)方式
添加依賴pom.xml
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>apache-cxf</artifactId>
<version>2.7.18</version>
<type>pom</type>
</dependency>
這里選擇的版本是2.7.18,不算新的版本砂蔽,cxf由于依賴太多太多洼怔,而且每個(gè)版本升級(jí),兼容性都比較差左驾,一旦整合到既有系統(tǒng)镣隶,輕易不敢升級(jí)。這里需要根據(jù)需求诡右,刪減一些不用的jar
web.xml配置
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:cxf-beans.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
這里面有兩部分安岂,一個(gè)是cxf的配置,另一個(gè)是整合spring啟動(dòng)
接口定義類CxfService
@WebService
public interface CxfService {
public String sayHello(String name);
}
主要是利用@WebService
這個(gè)注解
接口實(shí)現(xiàn)類
@WebService()
public class CxfServiceImpl {
public String sayHello(String name) {
return "hello: " + name;
}
}
主要是利用@WebService()
這個(gè)注解帆吻。
spring配置cfx-beans.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://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"
>
<jaxws:endpoint id="cxfService" implementor="com.critc.cxf.CxfServiceImpl" address="/cxfService"/>
</beans>
主要是利用jaxws這種方式域那,來發(fā)布WebService
都做完后,部署啟動(dòng)猜煮,在地址欄輸入:http://localhost:8080/services
啟動(dòng)顯示
查看WSDL
查看WSDL
動(dòng)態(tài)調(diào)用
public class TestCxf {
public static void main(String[] args) {
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
org.apache.cxf.endpoint.Client client = dcf
.createClient("http://localhost:8080/services/cxfService?wsdl");
// url為調(diào)用webService的wsdl地址
QName name = new QName("http://cxf.critc.com/", "sayHello");
// namespace是命名空間次员,methodName是方法名
String xmlStr = "張三";
// paramvalue為參數(shù)值
Object[] objects;
try {
objects = client.invoke(name, xmlStr);
System.out.println(objects[0].toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
需要四個(gè)參數(shù),
wsdl的地址:http://localhost:8080/services/cxfService?wsdl
namespace:http://cxf.critc.com/
方法名:sayHello
參數(shù)列表:張三
然后就可以調(diào)用了
調(diào)用結(jié)果.png
CXF可以和Spring很好的整好到一起翠肘,而且CXF還有很多其他功能檐束,并不單單是發(fā)布WebService這一個(gè)功能。有興趣的可以仔細(xì)研究被丧。