SpringBoot2.1.6 整合CXF 實現Webservice


SpringBoot2.1.6 整合CXF 實現Webservice

前言

最近LZ產品需要對接公司內部通訊工具,采用的是Webservice接口。產品框架用的SpringBoot2.1.6,於是采用整合CXF的方式實現Webservice接口。在這里分享下整合的demo。

代碼實現
  1. 項目結構

    直接通過idea生成SpringBoot項目,也可以在http://start.spring.io生成。過於簡單,這里不贅述。

    ![1561728847121](

)

  1. POM文件引入。這里引入的版本是3.2.4

    <dependency>          
        <groupId>org.apache.cxf</groupId>          
        <artifactId>cxf-spring-boot-starter-jaxws</artifactId>          			           <version>3.2.4</version>      
    </dependency>
    
  2. 接口與接口實現類

    package com.xiaoqiang.cxf.service;
    import com.xiaoqiang.cxf.entity.Student;
    import javax.jws.WebMethod;
    import javax.jws.WebService;
    import java.util.List;
    
    /**
     * IStudentService <br>
     * 〈〉
     *
     * @author XiaoQiang
     * @create 2019-6-27
     * @since 1.0.0
     */
    @WebService(targetNamespace = "http://service.cxf.xiaoqiang.com/") //命名一般是接口類的包名倒序
    public interface IStudentService {
    
        @WebMethod  //聲明暴露服務的方法,可以不寫
        List<Student> getStudentInfo();
    }
    
    package com.xiaoqiang.cxf.service.impl;
    
    import com.xiaoqiang.cxf.entity.Student;
    import com.xiaoqiang.cxf.service.IStudentService;
    import org.springframework.stereotype.Component;
    import javax.jws.WebService;
    import java.util.ArrayList;
    import java.util.List;
    /**
     * StudentServiceImpl <br>
     * 〈學生接口實現類〉
     *
     * @author XiaoQiang
     * @create 2019-6-27
     * @since 1.0.0
     */
    @WebService(serviceName = "studentService"//服務名
            ,targetNamespace = "http://service.cxf.xiaoqiang.com/" //報名倒敘,並且和接口定義保持一致
            ,endpointInterface = "com.xiaoqiang.cxf.service.IStudentService")//包名
    @Component
    public class StudentServiceImpl implements IStudentService {
    
        @Override
        public List<Student> getStudentInfo() {
            List<Student> stuList = new ArrayList<>();
            Student student = new Student();
            student.setAge(18);
            student.setScore(700);
            student.setName("小強");
            stuList.add(student);
            return stuList;
    
        }
    }
    
    
  3. 配置類

    package com.xiaoqiang.cxf.config;
    
    import com.xiaoqiang.cxf.service.IStudentService;
    import org.apache.cxf.Bus;
    import org.apache.cxf.jaxws.EndpointImpl;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import javax.xml.ws.Endpoint;
    /**
     * CxfConfig <br>
     * 〈cxf配置類〉
     * @desription cxf發布webservice配置
     * @author XiaoQiang
     * @create 2019-6-27
     * @since 1.0.0
     */
    @Configuration
    public class CxfConfig {
    
        @Autowired
        private Bus bus;
    
        @Autowired
        private IStudentService studentService;
    
        /**
         * 站點服務
         * @return
         */
        @Bean
        public Endpoint studentServiceEndpoint(){
            EndpointImpl endpoint = new EndpointImpl(bus,studentService);
            endpoint.publish("/studentService");
            return endpoint;
        }
    }
    
    
  4. 啟動Application

    http://ip:端口/項目路徑/services/studentService?wsdl 查看生成的wsdl

測試
package com.xiaoqiang.cxf;

import com.xiaoqiang.cxf.entity.Student;
import com.xiaoqiang.cxf.service.IStudentService;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class CxfApplicationTests {
	private Logger logger = LoggerFactory.getLogger(CxfApplication.class);
	@Test
	public void contextLoads() {
	}
	/**
	 * 方法一:動態客戶端調用
	 */
	@Test
	public void DynamicClient(){

		JaxWsDynamicClientFactory jwdcf = JaxWsDynamicClientFactory.newInstance();
		Client client = jwdcf.createClient("http://localhost:8080/services/studentService?wsdl");
		Object[] objects = new Object[0];

		try {
			objects = client.invoke("getStudentInfo");
			logger.info("獲取學生信息==>{}",objects[0].toString());
			System.out.println("invoke實體:"+((ArrayList) objects[0]).get(0).getClass().getPackage());
			for(int i=0 ; i< ((ArrayList)objects[0]).size() ; i++){
				Student student = new Student();
				BeanUtils.copyProperties(((ArrayList) objects[0]).get(0),student);
				logger.info("DynamicClient方式,獲取學生{}信息==> 姓名:{},年齡:{},分數:{}",i+1,
						student.getName(),student.getAge(),student.getScore());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 代理類工廠
	 */
	@Test
	public void ProxyFactory(){

		String address = "http://localhost:8080/services/studentService?wsdl";
		//代理工廠
		JaxWsProxyFactoryBean factoryBean = new JaxWsProxyFactoryBean();
		//設置代理地址
		factoryBean.setAddress(address);
		//設置接口類型
		factoryBean.setServiceClass(IStudentService.class);
		//創建一個代理接口實現
		IStudentService studentService = (IStudentService) factoryBean.create();
		List<Student> studentList = studentService.getStudentInfo();
		for(int i=0 ; i< studentList.size() ; i++){
			Student student = studentList.get(i);
			logger.info("ProxyFactory方式,獲取學生{}信息==> 姓名:{},年齡:{},分數:{}",i+1,
					student.getName(),student.getAge(),student.getScore());
		}
	}

}

總結

1.接口與實現類中targetNamespace的注解是一定要寫的,指明能夠訪問的接口

2.targetNamespace,最后面有一個斜線,通常是接口報名的反向順序


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM