本文段摘录自 http://www.ibm.com/developerworks/cn/webservices/ws-pojo-springcxf/index.html
Apache CXF 是一个开放源代码框架,提供了用于方便地构建和开发 Web 服务的可靠基础架构。它允许创建高性能和可扩展的服务,您可以将这样的服务部署在 Tomcat 和基于 Spring 的轻量级容器中,以及部署在更高级的服务器上,例如 Jboss、IBM® WebSphere® 或 BEA WebLogic。
功能
该框架提供了以下功能:
Web 服务标准支持:CXF 支持以下 Web 服务标准:
Java API for XML Web Services (JAX-WS)
SOAP
Web 服务描述语言(Web Services Description Language ,WSDL)
消息传输优化机制(Message Transmission Optimization Mechanism,MTOM)
WS-Basic Profile
WS-Addressing
WS-Policy
WS-ReliableMessaging
WS-Security
前端建模 :CXF 提供了前端建模的概念,允许您使用不同的前端 API 来创建 Web 服务。API 允许您使用简单的工厂 Bean 并通过 JAX-WAS 实现来创建 Web 服务。它还允许您创建动态 Web 服务客户端.
工具支持:CXF 提供了用于在 Java Bean、Web 服务和 WSDL 之间进行转换的不同工具。它提供了对 Maven 和 Ant 集成的支持,并无缝地支持 Spring 集成。
** RESTful 服务支持**:CXF 支持代表性状态传输(Representational State Transfer,RESTful )服务的概念,并支持 Java 平台的 JAX-RS 实现。
对不同传输和绑定的支持:CXF 支持不同种类的传输,从 XML 到逗号分隔值 (CSV)。除了支持 SOAP 和 HTTP 协议绑定之外,它还支持 Java Architecture for XML Binding (JAXB) 和 AEGIS 数据绑定。
对非 XML 绑定的支持:CXF 支持非 XML 绑定,例如 JavaScript Object Notation (JSON) 和 Common Object Request Broker Architecture (CORBA)。它还支持 Java 业务集成(Java Business Integration,JBI)体系架构和服务组件体系架构(Service Component Architecture,SCA)。
Eclipse
Maven
Tomcat 8.0
测试软件
SoapUI 5.2.1
下载Apache CXF 压缩包
构建Maven项目(使用archetype,项目名称为 cxf_my_example)
org.apache.cxf.archetype
cxf-jaxws-javafirst 3.1.4
将项目发布到Tomcat服务器 端口 8080 运行服务器
访问wsdl地址 http://localhost:8080/cxf_my_example/HelloWorld?wsdl
响应wsdl文件表示服务发布成功
项目主要引用包(Maven自动配置其它包):
org.apache.cxf
cxf-rt-frontend-jaxws
3.1.4
org.apache.cxf
cxf-rt-transports-http
3.1.4
org.springframework
spring-web
4.1.7.RELEASE
定义接口:
@WebService注解只是标注该接口为Web服务的访问接口,@WebParam标注参数名称,便于生成友好的WSDL.
@WebService
public interface HelloWorld {
String sayHi(@WebParam(name="text")String text);
}
定义实现:
实现类也需要标注@WebService,并设置参数endpointInterface指定实现的接口的全限定名称
@WebService(endpointInterface = "my.zhwc.cxf_my_example.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
public String sayHi(String text) {
return "Hello " + text;
}
}
SpringBean 配置:
现在已经创建了一个接口和实现,使用 CXF,可以使用 JAX-WS 前端使其成为实际的服务组件.
Web.XML配置:
现在,使用Spring加载配置文件,注册CXF Servlet 处理所有客户端的访问请求.
contextConfigLocation
WEB-INF/beans.xml
org.springframework.web.context.ContextLoaderListener
CXFServlet
CXF Servlet
org.apache.cxf.transport.servlet.CXFServlet
1
CXFServlet
/*
打开SoapUI,新建一个空项目,添加wsdl地址[http://localhost:8080/cxf_my_example/HelloWorld?wsdl]
在请求中填入参数 cong,返回结果 Hello cong ,如下:
cong
Hello cong
我们直接在服务端工程中编写客户端代码,这样无需使用CXF 的 wsdl2java工具生成客户端接口代码了.
import my.zhwc.cxf_my_example.HelloWorld;
public class Client {
public static void main(String[] args) {
ClassPathXmlApplicationContext context
= new ClassPathXmlApplicationContext(new String[]
{"classpath:my/zhwc/cxf_my_example/client/client-beans.xml"});
HelloWorld client = (HelloWorld)context.getBean("client");
System.out.println(client.sayHi("Cong"));
System.exit(0);
}
}
在服务端已发布的状态下,运行Client.java 可得输出 Hello Cong
http://www.ibm.com/developerworks/cn/webservices/ws-pojo-springcxf/index.html