1.添加相关依赖

在SpringBoot骨架工程的基础上,导入以下Jar包

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web-services</artifactId>
  4. <version>2.5.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.apache.cxf</groupId>
  8. <artifactId>cxf-rt-frontend-jaxws</artifactId>
  9. <version>3.4.3</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.apache.cxf</groupId>
  13. <artifactId>cxf-rt-transports-http</artifactId>
  14. <version>3.4.3</version>
  15. </dependency>

2、创建服务端接口

  1. @WebService(name = "DemoService", // 暴露服务名称
  2. targetNamespace = "http://service.webserviceprovider.lwq.com") // 命名空间,一般是接口的包名倒序
  3. public interface DemoService {
  4. public String sayHello(@WebParam(name = "name") String name);
  5. }

3、创建接口实现类

  1. @Component
  2. @WebService(name = "Demoservice", // 与接口中指定的name一致
  3. targetNamespace = "http://service.webserviceprovider.lwq.com", // 与接口中的命名空间一致,一般是接口的包名倒序
  4. endpointInterface = "com.lwq.webserviceprovider.service.DemoService") // 接口地址
  5. public class DemoServiceImpl implements DemoService {
  6. @Override
  7. public String sayHello(String name) {
  8. return "你好:" + name;
  9. }
  10. }

4、创建CXF配置类

  1. @Configuration
  2. public class CxfConfig {
  3. @Bean
  4. public ServletRegistrationBean createServletRegistrationBean() {
  5. return new ServletRegistrationBean(new CXFServlet(), "/demo/*");
  6. }
  7. @Bean(name = Bus.DEFAULT_BUS_ID)
  8. public SpringBus springBus() {
  9. return new SpringBus();
  10. }
  11. @Bean
  12. public DemoService demoService() {
  13. return new DemoServiceImpl();
  14. }
  15. @Bean
  16. public Endpoint endpoint() {
  17. EndpointImpl endpoint = new EndpointImpl(springBus(), demoService());
  18. endpoint.publish("/api");
  19. return endpoint;
  20. }
  21. }

5、启动并测试

启动服务端,并用SoapUI访问 http://localhost:8080/demo/api?wsdl,找到sayHello方法,输入参数,查看结果。

image.png