SpringBoot发布WebService接口(整合CXF)
写了两天,出现各种bug,终于搞出来了,记录一下。
1.导入相关依赖(我用的parent是2.1.3.RELEASE版本)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-spring-boot-starter-jaxws</artifactId>
<version>3.2.6</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.1.12</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>3.1.12</version>
</dependency>
2.创建接口DemoService
package com.webService.javaplat.modular.system.service;
import javax.jws.WebService;
@WebService(name = "DemoService", // 暴露服务名称
targetNamespace = "http://service.system.modular.javaplat.webService.com"// 命名空间,一般是接口的包名倒序
)
public interface DemoService {
@WebMethod(operationName="sayHello",action = "sayHello")
String sayHello(String user);
}
3.创建实现类DemoServiceImpl
import com.zhicheng.javaplat.modular.system.service.DemoService;
import javax.jws.WebService;
import java.util.Date;
@WebService(serviceName = "DemoService", // 与接口中指定的name一致
targetNamespace = "http://service.system.modular.javaplat.webService.com", // 与接口中的命名空间一致,一般是接口的包名倒
endpointInterface = "com.webService.javaplat.modular.system.service.DemoService"// 接口地址
)
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String user) {
return "Hello,现在时间:"+"("+new Date()+")";
}
}
4.CXF配置
import com.zhicheng.javaplat.modular.system.service.DemoService;
import com.zhicheng.javaplat.modular.system.service.impl.DemoServiceImpl;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.xml.ws.Endpoint;
@Configuration
public class CxfConfig {
@SuppressWarnings("all")
@Bean(name = "cxfServlet")
public ServletRegistrationBean cxfServlet() {
//创建服务并指定服务名称
return new ServletRegistrationBean(new CXFServlet(),"/cxf/*");
}
@Bean(name = Bus.DEFAULT_BUS_ID)
public SpringBus springBus() {
return new SpringBus();
}
@Bean
public DemoService demoService(){
return new DemoServiceImpl();
}
/**
* 注册WebServiceDemoService接口到webservice服务
* @return
*/
@Bean
public Endpoint endpoint() {
EndpointImpl endpoint = new EndpointImpl(springBus(),demoService());
endpoint.publish("/api");
return endpoint;
}
}
5.在浏览器输入http://localhost:8081/cxf/api?wsdl(8081是我自己设置的端口,看自己情况而定) 出现上面图片即表示成功。
