Spring Boot+CXF快速搭建WebService


Cxf的springboot集成使用

特別注意,用jdk11請加上這個包,jdk11已經將該包移除了

     <dependency>
            <groupId>com.sun.xml.ws</groupId>
            <artifactId>jaxws-ri</artifactId>
            <version>2.3.3</version>
            <type>pom</type>
        </dependency>

 

 一:項目的目錄結構

 二:pon.xml環境依賴

 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 <!--   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> &lt;!&ndash; lookup parent from repository &ndash;&gt;
    </parent>-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.kexin</groupId>
    <artifactId>webservice</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>webservice</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>


        <!--WerbService CXF依賴-->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>3.2.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>3.2.6</version>
        </dependency>
   <!--     <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
        </dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
View Code

 

 三:webservice服務編寫

3.1實體編寫

package com.kexin.webservice.entity;

import java.io.Serializable;

/**
 * @Description:
 * @Author: 巫恆強
 * @Date: 2019/12/17 15:28
 */
public class User implements Serializable {
    private static final long serialVersionUID = -3628469724795296287L;

    private String userId;
    private String userName;
    private String email;


    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "userId='" + userId + '\'' +
                ", userName='" + userName + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}
View Code

 

3.2userservice服務接口

package com.kexin.webservice.service;



import com.kexin.webservice.entity.User;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import java.util.Map;


/**
 * @Description:
 * @Author: 巫恆強
 * @Date: 2019/12/17 15:29
 */
//@WebService(targetNamespace="http://service.springboot.mracale.com")如果不添加的話,動態調用invoke的時候,會報找不到接口內的方法,具體原因未知.
@WebService(targetNamespace="http://service.webservice.kexin.com")
public interface UserService {

    @WebMethod//標注該方法為webservice暴露的方法,用於向外公布,它修飾的方法是webservice方法,去掉也沒影響的,類似一個注釋信息。
    public User getUser(@WebParam(name = "userId") String userId);

    @WebMethod
    @WebResult(name="String",targetNamespace="")
    public String getUserName(@WebParam(name = "userId") String userId);

    @WebMethod
    @WebResult(name="Map")
    public Map<String, User> getAllUserData();
}

 

3.3userservice服務實現

package com.kexin.webservice.service.impl;


import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.jws.WebService;


import com.kexin.webservice.entity.User;
import com.kexin.webservice.service.UserService;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * @Author: 巫恆強
 * @Date: 2019/12/17 15:32
 */
/**
 * @ClassName:UserServiceImpl
 * @Description:測試服務接口實現類
 */
@WebService(serviceName="UserService",//對外發布的服務名
        targetNamespace="http://service.webservice.kexin.com",//指定你想要的名稱空間,通常使用使用包名反轉
        endpointInterface="com.kexin.webservice.service.UserService")//服務接口全路徑, 指定做SEI(Service EndPoint Interface)服務端點接口
@Component
public class UserServiceImpl implements UserService {

    private Map<String, User> userMap = new HashMap<String, User>();
    public UserServiceImpl() {
        System.out.println("向實體類插入數據");
        User user = new User();
        user.setUserId(UUID.randomUUID().toString().replace("-", ""));
        user.setUserName("mracale01");
        user.setEmail("mracale01@163.xom");
        userMap.put(user.getUserId(), user);

        user = new User();
        user.setUserId(UUID.randomUUID().toString().replace("-", ""));
        user.setUserName("mracale02");
        user.setEmail("mracale02@163.xom");
        userMap.put(user.getUserId(), user);

        user = new User();
        user.setUserId(UUID.randomUUID().toString().replace("-", ""));
        user.setUserName("mracale03");
        user.setEmail("mracale03@163.xom");
        userMap.put(user.getUserId(), user);
    }
    @Override
    public String getUserName(String userId) {
        return "userId為:" + userId;
    }

    @Override
    public Map<String, User> getAllUserData() {
        return userMap;
    }

    @Override
    public User getUser(String userId) {
        System.out.println("userMap是:"+userMap);
        return userMap.get(userId);
    }

}

 

四:webservice的全局配置

package com.kexin.webservice.config;

import com.kexin.webservice.service.UserService;
import com.kexin.webservice.service.impl.UserServiceImpl;
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.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.xml.ws.Endpoint;
/**
 * @Description:
 * @Author: 巫恆強
 * @Date: 2019/12/17 15:37
 */
@Configuration
public class CxfConfig {

    /**
     * 此方法作用是改變項目中服務名的前綴名,此處127.0.0.1或者localhost不能訪問時,請使用ipconfig查看本機ip來訪問
     * 此方法被注釋后:wsdl訪問地址為http://127.0.0.1:8080/services/user?wsdl
     * 去掉注釋后:wsdl訪問地址為:http://127.0.0.1:8080/kexin/webservice/user?wsdl
*
@return */ @SuppressWarnings("all") @Bean public ServletRegistrationBean dispatcherServlet() { return new ServletRegistrationBean(new CXFServlet(), "/kexin/webservice/*"); } @Bean(name = Bus.DEFAULT_BUS_ID) public SpringBus springBus() { return new SpringBus(); } @Bean public UserService userService() { return new UserServiceImpl(); } @Bean public Endpoint endpoint() { EndpointImpl endpoint=new EndpointImpl(springBus(), userService());//綁定要發布的服務 endpoint.publish("/user"); //顯示要發布的名稱 return endpoint; } }

 

 

五:服務啟動后通過配置的地址訪問wsdl文件  http://127.0.0.1:8080/kexin/webservice/user?wsdl

 

 

 六:java的調用方式 client編寫

package com.kexin.webservice.Test;


import com.kexin.webservice.entity.User;
import com.kexin.webservice.service.UserService;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

import java.util.Map;

/**
 * @ClassName:CxfClient
 * @Description:webservice客戶端:
 *                 該類提供兩種不同的方式來調用webservice服務
 *              1:代理工廠方式
 *              2:動態調用webservice
 */

public class CxfClient {

    public static void main(String[] args) {
//        CxfClient.main1();
        CxfClient.main2();
    }

    /**
     * 1.代理類工廠的方式,需要拿到對方的接口地址
     */
    public static void main1() {
        try {
            // 接口地址
            String address = "http://127.0.0.1:8080/kexin/webservice/user?wsdl";
            // 代理工廠
            JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
            // 設置代理地址
            jaxWsProxyFactoryBean.setAddress(address);
            // 設置接口類型
            jaxWsProxyFactoryBean.setServiceClass(UserService.class);
            // 創建一個代理接口實現
            UserService us = (UserService) jaxWsProxyFactoryBean.create();
            // 數據准備
//            String userId = "maple";
            // 調用代理接口的方法調用並返回結果
//            String result = us.getUserName(userId);
            Map<String, User> userMaps= us.getAllUserData();
            System.out.println("返回結果:" + userMaps);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 2:動態調用
     */
    public static void main2() {
        // 創建動態客戶端
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient("http://127.0.0.1:8080/kexin/webservice/user?wsdl");
        // 需要密碼的情況需要加上用戶名和密碼
        // client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME, PASS_WORD));
        Object[] objects = new Object[0];
        try {
            // invoke("方法名",參數1,參數2,參數3....);
            objects = client.invoke("getUserName", "maple");
            System.out.println("返回數據:" + objects[0]);
        } catch (java.lang.Exception e) {
            e.printStackTrace();
        }
    }
}
View Code


免責聲明!

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



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