正文
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
demo.ws
soap_cxf
1.0-SNAPSHOT
UTF-8
3.0.0
org.apache.cxf
cxf-rt-frontend-jaxws
${cxf.version}
org.apache.cxf
cxf-rt-transports-http-jetty
${cxf.version}
如果您目前还没有使用 Maven,那么就需要从以下地址下载 CXF 的相关 jar 包,并将其放入应用中。
http://cxf.apache.org/download.html
第二步:写一个 WS 接口及其实现
接口部分:
package demo.ws.soap_cxf;
import javax.jws.WebService;
@WebService
public interface HelloService {
String say(String name);
}
实现部分:
package demo.ws.soap_cxf;
import javax.jws.WebService;
@WebService
public class HelloServiceImpl implements HelloService {
public String say(String name) {
return "hello " + name;
}
}
这里简化了实现类上的 WebService 注解的配置,让 CXF 自动为我们取默认值即可。
第三步:写一个 JaxWsServer 类来发布 WS
package demo.ws.soap_cxf;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
public class JaxWsServer {
public static void main(String[] args) {
JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
factory.setAddress("http://localhost:8080/ws/soap/hello");
factory.setServiceClass(HelloService.class);
factory.setServiceBean(new HelloServiceImpl());
factory.create();
System.out.println("soap ws is published");
}
}
发布 WS 除了以上这种基于 JAX-WS 的方式以外,CXF 还提供了另一种选择,名为 simple 方式。
通过 simple 方式发布 WS 的代码如下:
package demo.ws.soap_cxf;
import org.apache.cxf.frontend.ServerFactoryBean;
public class SimpleServer {
public static void main(String[] args) {
ServerFactoryBean factory = new ServerFactoryBean();
factory.setAddress("http://localhost:8080/ws/soap/hello");
factory.setServiceClass(HelloService.class);
factory.setServiceBean(new HelloServiceImpl());
factory.create();
System.out.println("soap ws is published");
}
}
注意:以 simple 方式发布的 WS,不能通过 JAX-WS 方式来调用,只能通过 simple 方式的客户端来调用,下文会展示 simple 方式的客户端代码。
第四步:运行 JaxWsServer 类
当 JaxWsServer 启动后,在控制台中会看到打印出来的一句提示。随后,在浏览器中输入以下 WSDL 地址:
ttp://localhost:8080/ws/soap/hello?wsdl
注意:通过 CXF 内置的 Jetty 发布的 WS,仅能查看 WSDL,却没有像 RI 那样的 WS 控制台。
可见,这种方式非常容易测试与调试,大大节省了我们的开发效率,但这种方式并不适合于生产环境,我们还是需要依靠于 Tomcat 与 Spring。
那么,CXF 在实战中是如何集成在 Spring 容器中的呢?见证奇迹的时候到了!
3. 在 Web 容器中使用 Spring + CXF 发布 WS
Tomcat + Spring + CXF,这个场景应该更加接近我们的实际工作情况,开发过程也是非常自然。
第一步:配置 Maven 依赖
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
demo.ws
soap_spring_cxf
1.0-SNAPSHOT
war
UTF-8
4.0.5.RELEASE
3.0.0
org.springframework