1. 程式人生 > >webservice之cxf實現[web專案中基於maven與spring整合]

webservice之cxf實現[web專案中基於maven與spring整合]

webservice現開發的已實現元件不少,使用過的就有xfire及cxf.
cxc基於maven與spring整合過程如下:

STEP 1. 依賴包新增

在pom.xml檔案的標籤中增加如下(版本號依個人需要調整):

    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf</artifactId>
        <version>2.7.7</version>
        <type
>
pom</type> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>2.7.7</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId
>
<artifactId>cxf-rt-transports-http</artifactId> <version>2.7.7</version> </dependency>

STEP 2. 編寫服務類程式碼

介面定義:

package test.service;

import javax.jws.WebService;

/**
 * 
 * @Description: webservice測試服務
 * @author LeonWang
 * @date 2016-2-2 下午2:46:33 
 *
 */
@WebService public interface MyService { public void sayHi(String name); }

介面實現

package test.service.impl;

import javax.jws.WebService;

import test.service.MyService;
@WebService(endpointInterface = "test.service.MyService")
public class MyServiceImpl implements MyService {
    @Override
    public void sayHi(String name) {
        System.out.println("hello,"+name);
    }

}

STEP 3.配置springbean及webservice釋出

建立cxf-servlet.xml將其放在spring配置檔案掃描路徑下

<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.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-servlet.xml"/>
    <bean id="myService" class="test.service.impl.MyServiceImpl" />
    <jaxws:endpoint id="testService" implementor="#myService" address="/testService"/>
</beans>

說明:
1. cxf-servlet.xml中import匯入的檔案不用自己建立,這是在依賴包中的。
2. webservice釋出配置中implementor可以直接吸入實現類,如:

<jaxws:endpoint id="testService" implementor="test.service.impl.MyServiceImpl" address="/testService"/>

3.address引數是重點,這是webservice釋出後其wsdl的相對路徑,其絕對路徑為應用訪問路徑/cxf攔截路徑/address?wsdl

STEP 4.配置webservice攔截

在web.xml中增加cxf的攔截配置,如下:

<servlet>
        <servlet-name>cxf</servlet-name>
        <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>cxf</servlet-name>
    <url-pattern>/services/*</url-pattern>
</servlet-mapping>

STEP 5.測試服務是否釋出成功

部署並啟動服務,訪問wsdl,本配置訪問如下:
http://localhost:8001/webserviceTest/services/testService?wsdl
我的專案部署在本地,埠8001,應用訪問名稱為webserviceTest,cxf攔截配置為/services/*,釋出相對地址為/testService.