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