初识Apache CXF

来源:互联网 发布:c语言输入多组数据 编辑:程序博客网 时间:2024/05/18 01:05

一、下载地址:http://cxf.apache.org,下载时可以选择二进制压缩包或源码包;下载解压后的目录如下:

二、使用CXF开发webService的步骤:以经典的HelloWorld为例

1、创建java项目,导入CXF的lib文件夹下所需的常用jar包;

2、编写webService接口及期实现类;

package com.ylink.cxf;
public interface HelloWorldService {
public String sayHello(String name);
}

package com.ylink.cxf.impl;
import com.ylink.cxf.HelloWorldService;
public class HelloWorldServiceImpl implements HelloWorldService {
@Override
public String sayHello(String name) {
return name + "say: Hello World";
}
}

3、使用ServerFactoryBean创建服务端

package com.ylink.cxf.service;
import org.apache.cxf.frontend.ServerFactoryBean;
import com.ylink.cxf.HelloWorldService;
import com.ylink.cxf.impl.HelloWorldServiceImpl;
public class Service {
public static void main(String[] args) {
HelloWorldService impl = new HelloWorldServiceImpl();
ServerFactoryBean bean = new ServerFactoryBean();
//指定类的实现服务(接口)
bean.setServiceClass(HelloWorldService.class);
//公布service的访问地址
bean.setAddress("http://localhost:8080/HelloWorld");
//设置bean的实现(接口的实现类)
bean.setServiceBean(impl);
//发布webService
bean.create();
}
}

测试:运行Service类,如果控制台没有错误输出,打开浏览器,在地址栏输入发布的service访问地址http://localhost:8080/HelloWorld,如果页面正确显示WSDL,则证明web service发布成功。

三、使用CXF的ClientProxyFactoryBean创建客户端

package com.ylink.cxf.client;
import org.apache.cxf.frontend.ClientProxyFactoryBean;
import com.ylink.cxf.HelloWorldService;
public class Client {
public static void main(String[] args) {
ClientProxyFactoryBean bean = new ClientProxyFactoryBean();
//指定代理实现(接口)
bean.setServiceClass(HelloWorldService.class);
//指定代理地址(即服务端发布的访问地址)
bean.setAddress("http://localhost:8080/HelloWorld");
//创建代理对象(接口)
HelloWorldService service = (HelloWorldService) bean.create();
System.out.println(service.sayHello("张三"));
}
}

核心代码如下图所示:


四、使用CXF传递对象,如javaBean、List等,与以上代码(传递字符串)基本无差别;

五、CXF与Spring的集成

1、导入spring框架(spring-core、spring-beans、spring-context、spring-web......)、CXF框架所需的jar包;

2、开发服务接口及其实现类;

3、配置spring配置文件applicationContext.xml;


4、配置web.xml文件,用于集成CXF和spring;


5、客户端applicationContext.xml中的配置


6、客户端测试通讯





0 0