用cxf框架搭建webservice服務(spring的xml方式和springboot方式)

一、基於cxf框架,在spring框架中搭建webservice服務

步驟1,創建一個maven項目,首先導入spring相關依賴,再導入cxf依賴,配置tomcat插件等相關插件

 <properties>
		<spring.version>4.2.4.RELEASE</spring.version>
  </properties>
  
  
  <dependencies>
		<!-- spring -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.6.8</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

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

	</dependencies>
	
	 <build>
	<pluginManagement>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.2</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
					<encoding>UTF-8</encoding>
					<showWarnings>true</showWarnings>
				</configuration>
			</plugin>
			<plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <port>8080</port>
                    <path>/</path>
                    <uriEncoding>UTF-8</uriEncoding>
                    <server>tomcat7</server>
                </configuration>
            </plugin>
		</plugins>
	</pluginManagement>
  </build>

2.寫一個簡單接口,功能描述是輸入城市名稱,返回當前城市天氣情況,註解@WebParam(name="cityName")表示參數名

import javax.jws.WebParam;
import javax.jws.WebService;

@WebService
public interface WeatherService {
	
	public String getCityInfo(@WebParam(name="cityName")String cityName);

}

3.實現類

public class WeatherServiceImpl implements WeatherService {
	@Override
	public String getCityInfo(String cityName) {
		String res = "";
		if(cityName.equals("北京")) {
			res = cityName+":大雨";
		}
		if(cityName.equals("上海")) {
			res = cityName+":多雲";
		}
		return res;
	}
}

4.spring的配置文件做如下配置

<?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:cxf="http://cxf.apache.org/core"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:jaxrs="http://cxf.apache.org/jaxrs"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://cxf.apache.org/core
        http://cxf.apache.org/schemas/core.xsd
        http://cxf.apache.org/jaxws
        http://cxf.apache.org/schemas/jaxws.xsd
        http://cxf.apache.org/jaxrs
        http://cxf.apache.org/schemas/jaxrs.xsd
        ">

	<!-- 服務類,將服務類注入到spring容器 -->
	<bean id="weather" class="com.enjoy.ws.WeatherServiceImpl"></bean>
	
	<!-- 將服務發佈 -->
	<jaxws:server address="/weather">
		<jaxws:serviceBean>
			<ref bean="weather"/>
		</jaxws:serviceBean>
	</jaxws:server>
</beans>	

5.web.xml做如下配置

<!--加載spring配置文件-->
<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext*.xml</param-value>

	</context-param>
<!--配置監聽-->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

<!--配置cxf的servlet-->
	<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>/ws/*</url-pattern>
	</servlet-mapping>

6.啓動項目,run as —> maven build .輸入tomcat7:run,通過配置的tomcat插件啓動項目

瀏覽器輸入 localhost:8080/ws/weather?wsdl

ip+端口+配置的tomcat插件的<path>標籤的內容+web.xml配置的cxf的攔截路徑+spring配置文件將服務發佈的address的值+ ?wsdl

得到如下結果則證明發布成功

 

這裏是關於發佈服務的詳細描述。

7.寫一個main方法測試調用服務

需引入如下依賴

<dependency>
        <groupId>axis</groupId>
        <artifactId>axis</artifactId>
        <version>1.4</version>
    </dependency>
import javax.xml.namespace.QName;
import javax.xml.rpc.Call;

import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;

public class Weather {
	
	public static void main(String[] args) throws Exception {
		Service service = new Service();
		Call call = service.createCall();
		call.setTargetEndpointAddress("http://localhost:8080/ws/weather?wsdl");//服務地址
		call.setOperationName(new QName("http://ws.enjoy.com/","getCityInfo"));
	 	  //參數設置,這裏寫cityName是服務端通過註解配置的,如果服務端不指定,需要寫args0
        call.addParameter("cityName",XMLType.XSD_STRING,javax.xml.rpc.ParameterMode.IN);
	    call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// 設置返回類型
	    String res = (String) call.invoke(new Object[]{"北京"});
		System.out.println(res);
	}

}

得到結果,服務調用成功

 

二、springboot方式和xml方式本質上一樣,下面對照上面步驟,做springboot方式的搭建。

1.創建maven項目,選擇war包,引入依賴,注意選擇parent的版本,這裏有一個坑,下面具體說

<parent>
  		<groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
  </parent>
  
  <dependencies>
      
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
      
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        
        <dependency> 
			<groupId>org.apache.cxf</groupId> 
			<artifactId>cxf-rt-frontend-jaxws</artifactId> 
			<version>3.3.0</version> 
		</dependency> 
		
		<dependency> 
			<groupId>org.apache.cxf</groupId> 
			<artifactId>cxf-rt-transports-http</artifactId> 
			<version>3.3.0</version> 
		</dependency>
        
    </dependencies>

2.寫服務接口

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

@WebService
public interface WeatherService {
	
	@WebMethod
	@WebResult(name = "String")
	public String getCityInfo(@WebParam(name="cityName")String cityName);
	
}

3.寫接口實現類,這裏的service註解是將這個實現類注入到spring容器中,也可以通過配置類將其注入

import org.springframework.stereotype.Service;
import com.enjoy.service.WeatherService;
@Service
public class WeatherServiceImpl implements WeatherService{

	@Override
	public String getCityInfo(String cityName) {
		String res = "";
		if(cityName.equals("北京")) {
			res = cityName+":大雨";
		}
		if(cityName.equals("上海")) {
			res = cityName+":多雲";
		}
		return res;
	}
}

4.配置類,配置cxf的攔截,配置WeatherServiceImpl服務路徑

import javax.xml.ws.Endpoint;
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.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.enjoy.service.WeatherService;


@Configuration
public class WSConfig {
	
		@Autowired
		private WeatherService WeatherServiceImpl;
	
	//這個相當於在web.xml中配置cxf的攔截配置
		@SuppressWarnings({ "rawtypes", "unchecked" })
		@Bean(name="disServlet")
        /*這裏有一個坑,如果bean的name屬性不指定,則默認引用方法名稱dispatcherServlet,
          在不同的springboot版本中效果不同,在2.0.3中可以正常啓動,高版本會報錯,
          這是因爲會覆蓋掉默認的dispatcherServlet,所以這個注入的bean的名字不能用 
          dispatcherServlet,要不就在bean的name屬性上指定,要麼就將方法名換成別的
        */
		public ServletRegistrationBean dispatcherServlet() {
			return new ServletRegistrationBean(new CXFServlet(), "/ws/*");
		}
		
		@Bean(name = Bus.DEFAULT_BUS_ID)
		public SpringBus springBus() {
		    return new SpringBus();
		}
		
		@Bean
		public Endpoint endpoint() {
            //指定weatherService服務的路徑
		    EndpointImpl endpoint = new EndpointImpl(springBus(), WeatherServiceImpl);
		    endpoint.publish("/weather");
		    return endpoint;
		}

5.寫一個main方法啓動項目

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class WSWeatherApp {
	
	public static void main(String[] args) {
		SpringApplication.run(WSWeatherApp.class, args);
	}

}

6.測試,瀏覽器輸入localhost:8080/ws/weather?wsdl。

規則:ip+端口+配置的cxf攔截路徑+服務類路徑+?wsdl,由於springboot沒有配置項目路徑和端口,則默認沒有項目路徑和默認8080端口,想要修改則在配置文件中修改即可。

服務發佈成功

用上面的測試main方法,填好參數,測試得到返回值

import javax.xml.namespace.QName;
import javax.xml.rpc.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
public class Weather {
	
	public static void main(String[] args) throws Exception {
		Service service = new Service();
		Call call = service.createCall();
		call.setTargetEndpointAddress("http://localhost:8080/ws/weather?wsdl");//服務地址
		String add2= "http://service.enjoy.com/";
		call.setOperationName(new QName(add2,"getCityInfo"));
	 	  //參數設置
        call.addParameter("cityName",XMLType.XSD_STRING,javax.xml.rpc.ParameterMode.IN);
	    call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// 設置返回類型
	    String res = (String) call.invoke(new Object[]{"上海"});
		System.out.println(res);
	}

}

 

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