SpringBoot集成WebService

1)添加依赖

 <dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
    <version>3.3.4</version>
    <exclusions>
        <exclusion>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>

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

2)添加服务接口

public interface UserService {
    UserDTO getById(@WebParam(name="id") Integer id);
}

3)添加服务实现类

@Service
@WebService
        (
        targetNamespace = "http://www.xjs1919.com", 
        serviceName = "userService"
)
public class UserServiceImpl implements UserService {
    @Override
    public UserDTO getById(Integer id) {
        return new UserDTO(id, "hello_"+id);
    }
}

4)添加配置类

@Configuration
@Slf4j
public class WebServiceConfig {
 
    @Autowired
    private UserService userService;

    /**
     * 注入Servlet,注意beanName不能为dispatcherServlet
     */
    @Bean
    public ServletRegistrationBean cxfServlet() {
        return new ServletRegistrationBean(new CXFServlet(), "/webservice/*");
    }

    @Bean(name = Bus.DEFAULT_BUS_ID)
    public SpringBus springBus() {
        return new SpringBus();
    }

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

}

5)启动应用,查看服务列表

浏览器访问:http://localhost:8888/webservice
在这里插入图片描述
点击WSDL后面的连接可以查看WSDL地址和内容:
在这里插入图片描述

6)测试

@Test
public void testGetById(){
    JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
    Client client = dcf.createClient("http://localhost:8888/webservice/userService?wsdl");
    final ObjectMapper mapper = new ObjectMapper();
    try {
        Object[] objects = client.invoke("getById", 123);
        System.out.println(mapper.writeValueAsString(objects[0]));
    } catch (Exception e) {
        e.printStackTrace();;
    }
}

完整源码下载:https://github.com/xjs1919/enumdemo/tree/master/springboot-webservice

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值