1. 程式人生 > >Spring Boot+CXF搭建WebService

Spring Boot+CXF搭建WebService

project static transport odi uid mic 圖片 mage lan

Spring Boot WebService開發

技術分享圖片

需要依賴Maven的Pom清單

技術分享圖片
<?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 http://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.0.3.RELEASE</version> <relativePath/> </parent> <groupId>com.mracale</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-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> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
View Code

3. 開始編寫webService服務端

3.1 實體類entity

package com.mracale.springboot.Entity;

import java.io.Serializable;

/**
 *用戶實體類
 */
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 + \‘ +
                };
    }
}

3.2 服務接口

package com.mracale.springboot.Service;


import com.mracale.springboot.Entity.User;

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


//@WebService(targetNamespace="http://service.springboot.mracale.com")如果不添加的話,動態調用invoke的時候,會報找不到接口內的方法,具體原因未知.
@WebService(targetNamespace="http://service.springboot.mracale.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);

}

3.3 服務接口的實現類

package com.mracale.springboot.Service.impl;

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

import javax.jws.WebService;

import com.mracale.springboot.Entity.User;
import com.mracale.springboot.Service.UserService;
import org.springframework.stereotype.Component;

/**
 * @ClassName:UserServiceImpl
 * @Description:測試服務接口實現類
 */
@WebService(serviceName="UserService",//對外發布的服務名
        targetNamespace="http://service.springboot.mracale.com",//指定你想要的名稱空間,通常使用使用包名反轉
        endpointInterface="com.mracale.springboot.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("[email protected]");
        userMap.put(user.getUserId(), user);

        user = new User();
        user.setUserId(UUID.randomUUID().toString().replace("-", ""));
        user.setUserName("mracale02");
        user.setEmail("[email protected]");
        userMap.put(user.getUserId(), user);

        user = new User();
        user.setUserId(UUID.randomUUID().toString().replace("-", ""));
        user.setUserName("mracale03");
        user.setEmail("[email protected]");
        userMap.put(user.getUserId(), user);
    }
    @Override
    public String getUserName(String userId) {
        return "userId為:" + userId;
    }
    @Override
    public User getUser(String userId) {
        System.out.println("userMap是:"+userMap);
        return userMap.get(userId);
    }

}

3.4 發布webService的配置

package com.mracale.springboot.config;

import com.mracale.springboot.Service.UserService;
import com.mracale.springboot.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;

@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/soap/user?wsdl
     * @return
     */
    @SuppressWarnings("all")
    @Bean
    public ServletRegistrationBean dispatcherServlet() {
        return new ServletRegistrationBean(new CXFServlet(), "/soap/*");
    }

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

4. 項目啟動後的wsdl信息

技術分享圖片

5. 兩種調用方式

package com.mracale.springboot.client;

import com.mracale.springboot.Service.UserService;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

/**
 * @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/soap/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);
            System.out.println("返回結果:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 2:動態調用
     */
    public static void main2() {
        // 創建動態客戶端
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient("http://127.0.0.1:8080/soap/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();
        }
    }
}

6. 註意點.

誠如之前所說,如果接口的註解上不加targetNamespace的話,動態調用的時候,會報如下的錯誤。

技術分享圖片

Spring Boot+CXF搭建WebService