从清单 5 中可以看到,创建客户端 Bean 是非常容易的,就像创建服务端点一样容易。
JaxWsProxyFactory 用于创建
OrderProcess Web 服务的客户端 Bean。工厂 Bean 预期获得服务类 (
OrderProcess) 和您的服务的 URL。然后通过使用工厂 Bean 引用来创建客户端 Bean 存根
OrderProcess。
清单 5. client-bean.xml 客户端 Web 配置文件
| <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/s ... xf.apache.org/jaxws http://cxf.apache.org/schema/jaxws.xsd"> <bean id="client" class="demo.order.OrderProcess" factory-bean="clientFactory" factory-method="create"/> <bean id="clientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean"> <property name="serviceClass" value="demo.order.OrderProcess"/> <property name="address" value="http://localhost:8080/orderapp/OrderProcess"/> </bean> </beans> |
您将创建 Java 主程序,它使用 Spring 上下文来获取已定义的客户端 Bean,然后调用
processOrder 方法。
清单 6. 客户端代码
| public final class Client { public Client() { } public static void main(String args[]) throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"demo/order/client/client-beans.xml"}); OrderProcess client = (OrderProcess)context.getBean("client"); Order order = new Order(); String orderID = client.processOrder(order); System.out.println("Order ID: " + orderID); System.exit(0); }} |
运行程序
在运行程序之前,请在您的 C:\ 盘根文件夹下创建如图 1 所示的目录结构,并将本文介绍的组件放在其中:
- Java 代码放入包文件夹中。
- beans.xml 和 web.xml 放入 web\web-inf 文件夹中。
- client-beans.xml 将放入 demo\order\client 文件夹中。
图 1. 代码目录结构
对于构建、部署和运行
OrderProcess Web 服务和客户端,您将使用 Ant 工具。代码将部署在 Tomcat
服务器上。在 c:\orderapp 文件夹下使用
ant deploy 命令来部署代码。
应用程序文件夹 (c:\orderapp) 具有 Ant 构建文件。在运行上述命令之后,您的
orderapp 代码将作为 orderapp.war 文件部署在 Tomcat 服务器环境中。现在通过在 CATALINA_HOME\bin 文件夹下提供
catalina start 命令来启动 Tomcat Web 服务器。
orderapp 文件夹创建在 Tomcat 的 webapps 文件夹之下。启动服务器之后,通过输入
ant client 命令来运行该应用程序。输出将显示订单 ID(请参见图 2)。
图 2. 程序输出
结束语
本文简要描述了 CXF 框架的功能,并演示了它如何使您无需多少代码编写工作即可创建 Web 服务。您了解了使用 Bean 上下文文件的 Spring 与 CXF 的集成。您还研究了该框架如何将创建 Web 服务基础结构组件的实际语义抽象出来,并为您提供一个仅集中于 Web 服务创建的更简单的 API 外壳。
现在您已经了解了使用 CXF 来创建 Web 服务的基础,请继续关注本系列的第 2 部分,其中将向您介绍如何使用 CXF 和 Spring 将 POJO 公开为 Restful 服务。