抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

基础整合记录,方便下次梭哈。

近期公司某项目需要同步合作厂家的部分数据,其中有个功能需要我方提供接口供对方调用,通知我方数据有更新等。

1.前提

在已有的SpringBoot项目中,引入CXF依赖,编写配置代码及服务代码,最后进行发布。

本篇文章基于以下SDK、插件及版本。
Java - 1.8.0
Maven - 4.0.0
SpringBoot - 2.6.2

2.引入依赖

<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
    <version>3.5.0</version>
</dependency>

3.编写服务代码

新建一个服务接口,并实现它,用作提供接口对外发布的方法。

其中,接口名称(此处命名为NeuInform)、代码中的name及targetNamespace字段都可以根据实际情况自定义更改。

NeuInform.java:

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

@WebService(
        name = "NeuInform",
        targetNamespace = "http://com.ste.eams"
)
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface NeuInform {

    @WebMethod
    @WebResult(name = "String", targetNamespace = "http://com.ste.eams")
    String inform(@WebParam(name = "param", targetNamespace = "http://com.ste.eams") String param);

}

NeuInformImpl.java:

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.jws.WebService;

@WebService(
        name = "NeuInform",
        targetNamespace = "http://com.ste.eams"
)
@Service
@Component
public class NeuInformImpl implements NeuInform {

    @Override
    public String inform(String param) {
        String result = "处理完成";
        // 此处编写业务处理代码
        return result;
    }

}

4.编写配置代码

新建一个配置类,用于配置对外发布的接口方法及接口地址。

其中,endpoint方法中endpoint.publish方法传入的即为接口地址,可自定义。

CxfConfig.java:

import org.apache.cxf.Bus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.xml.ws.Endpoint;

@Configuration
public class CxfConfig {

    private final Bus bus;
    private final NeuInformImpl neuInform;

    public CxfConfig(Bus bus, NeuInformImpl neuInform) {
        this.bus = bus;
        this.neuInform = neuInform;
    }

    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(bus, neuInform);
        endpoint.publish("/neuInform");
        return endpoint;
    }

}

5.发布及测试

启动SpringBoot项目,会发现多了两行log:

Creating Service {http://com.ste.eams}NeuInformImplService from class com.ste.eams.service.NeuInform
Setting the server's publish address to be /neuInform

由浏览器访问发布的路径,(IP/端口/services/定义的路径?wsdl):

http://localhost:8080/services/neuInform?wsdl

可正常看到一个wsdl的XML即为启动成功,接口已发布完成。接下来可用SoapUI工具或编写代码进行测试,若无问题即可通知对方进行测试。

评论