cxf 프레임 워크를 사용하여 웹 서비스 서비스 구축 (spring xml 모드 및 springboot 모드)

1. cxf 프레임 워크를 기반으로 스프링 프레임 워크에서 웹 서비스 서비스를 구축합니다.

1 단계, Maven 프로젝트 생성, 먼저 스프링 관련 종속성 가져 오기, 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. 스프링 구성 파일은 다음과 같이 구성됩니다.

<?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. 프로젝트 시작-> maven 빌드 실행 tomcat7 : run, 구성된 tomcat 플러그인을 통해 프로젝트 시작

브라우저 입력 localhost : 8080 / ws / weather? wsdl

ip + port + 구성된 tomcat 플러그인의 <path> 태그 내용 + web.xml로 구성된 cxf의 차단 경로 + 스프링 구성 파일이 서비스를 게시 할 주소 값 +? wsdl

다음 결과는 릴리스가 성공적임을 증명합니다.

 

다음은 게시 서비스에 대한 자세한 설명입니다.

7. 호출 서비스를 테스트하기위한 메인 메소드 작성

다음 종속성을 도입해야합니다.

<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. 메이븐 프로젝트를 만들고, 전쟁 패키지를 선택하고, 의존성을 소개하고, 부모의 버전을 선택하는 데주의를 기울이고, 여기에 구덩이가 있습니다. 아래에서 자세히 설명하겠습니다.

<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. 인터페이스 구현 클래스를 작성합니다. 여기서 서비스 주석은이 구현 클래스를 스프링 컨테이너에 삽입하거나 구성 클래스를 통해 삽입 할 수 있습니다.

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. 프로젝트 시작을위한 주요 방법 작성

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이 없으며, 수정을 원할 경우 설정 파일에서 수정할 수 있습니다.

서비스가 성공적으로 게시되었습니다.

위의 테스트 주요 방법을 사용하고 매개 변수를 입력 한 다음 테스트하여 반환 값을 얻습니다.

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);
	}

}

 

추천

출처blog.csdn.net/csdnbeyoung/article/details/95546507