您的位置:首页 > 其它

使用CXF(JaxWsServerFactoryBean、ServerFactoryBean)编码的方式发布WebService服务

2013-04-15 13:35 691 查看
前面已经使用JDK自带的类库发布了一个简单的WebService。现在使用框架CXF的编码方式来发布一个WebService

CXF:Apache CXF 的前身叫 Apache CeltiXfire,现在已经正式更名为 Apache CXF 了,简称为 CXF。CXF 继承了 Celtix 和 XFire 两大开源项目的精华。

一般我们都是基于接口编程的、所以先提供一个接口类IHelloService

package com.service.cxf.code;

import javax.jws.WebService;
import javax.xml.ws.soap.SOAPBinding;
import javax.xml.ws.BindingType;

/**
* @author jackphang
* @date 2013-4-13
* @description
*/
@WebService
/**
*  将SOAP协议定义为1.2 Eclipse自带的WebService Brower只能解析soap1.1的协议
*  服务器端最好使用高版本的协议
*/
@BindingType(value = SOAPBinding.SOAP12HTTP_BINDING)
public interface IHelloService {

public String sayHello(String str);
}


具体的实现类HelloServiceImpl

package com.service.cxf.code;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
* @author jackphang
* @date 2013-4-13
* @description
*/
public class HelloServiceImpl implements IHelloService {
private static final SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");

@Override
public String sayHello(String str) {
System.out.println(sdf.format(new Date()) + "获得客户端数据:" + str);
return "hello : " + str;
}

public static void staticMethod() {
System.out.println("static方法不能在接口中定义,亦不能对外提供暴露");
}

public final void finalMethod() {
System.out.println("final方法不能在接口中定义,亦不能对外提供暴露");
}

}


发布服务的类ServiceCXF

package com.service.cxf.code;

import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;

/**
* @author jackphang
* @date 2013-4-13
* @description 编码的方式发布一个CXF 的WebService服务
*              使用JaxWsServerFactoryBean和ServerFactoryBean对外发布一个CXF服务,
*              推荐使用JaxWsServerFactoryBean方式, 它生成的wsdl比父类ServerFactoryBean更规范
*/
public class ServiceCXF {

/**
* @param args
*/
public static void main(String[] args) {
// 由该类对外发布一个服务,推荐使用该类
JaxWsServerFactoryBean server = new JaxWsServerFactoryBean();
// 或者由父类
// ServerFactoryBean server = new ServerFactoryBean();
// 对外提供服务的地址
server.setAddress("http://localhost:1111/hello");
// 提供服务的类型,此类必须加上@WebService的注解,不然,该类的实例中所有的方法将不对外暴露,但也不报错
server.setServiceClass(IHelloService.class);
// 提供服务的实例
server.setServiceBean(new HelloServiceImpl());
// 添加请求消息拦截器
server.getInInterceptors().add(new LoggingInInterceptor());
// 添加响应消息拦截器
server.getOutInterceptors().add(new LoggingOutInterceptor());
// 发布服务相当于JDK的 EndPoint.publish()
server.create();
}

}


运行ServiceCXF,我们的WebService就发布成功了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: