SpringBoot 的 Web Service 类型常见有 RESTful Web Service 和 SOAP Web Service 两种,RESTful 比较常用,但实际工作中仍有一些场景用到 SOAP Web Service。比如说一些公共平台的接口。
1.添加maven依赖
cxf的版本需要与spring boot版本匹配,否则会出现意想不到的错误。作者使用的为springboot版本为2.4.5。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxws</artifactId>
<version>3.4.1</version>
2.开发网络服务
分别编写接口类和实现类。
@WebService
public interface UserManagement {
@WebMethod
public User getUserByName(@WebParam (name="name") String name);
}
@Component
@WebService
public class UserManagementImpl implements UserManagement {
@Override
public User getUserByName(String name) {
User user=new User();
user.setName(name);
user.setAge(18);
user.setSex("boy");
return user;
}
}
3. 添加配置发布 Web Service
@Configuration
public class WebServiceConfig {
@Autowired
private UserManagement userManagement;
@Bean(name= Bus.DEFAULT_BUS_ID)
public SpringBus springBus(){
return new SpringBus();
}
@Bean
public Endpoint endpoint() {
EndpointImpl endpoint = new EndpointImpl(springBus(),userManagement);
endpoint.publish("/userManagement");
return endpoint;
}
// @Bean
// public ServletRegistrationBean dispatcherServlet() {
//
// /* “/soap/*” 为自己配置的 soap webservice 发布路径前缀 */
//
// return new ServletRegistrationBean(new CXFServlet(), "/soap/*");
//
// }
@Bean
public ServletRegistrationBean createServletRegistrationBean(){
/* “/soap/*” 为自己配置的 soap webservice 发布路径前缀 */
return new ServletRegistrationBean(new CXFServlet(), "/soap/*");
}
}
四. 运行SpringBoot项目
@SpringBootApplication
//@EnableAutoConfiguration
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class,args);
System.out.println("Hello world!");
}
}