CXF是apache旗下的开源框架,由Celtix+XFire这两门经典的框架组成,是一套非常流行的web service框架。采用代码优先或者WSDL优先来轻松地实现web services的发布和使用,同时它能与spring进行完美的结合。
官方文档:http://cxf.apache.org/docs/index.html
使用:
1.依赖的jar包
2.首先编写一个ws接口:
@WebService
public interface HelloService {
public String sayHi(String text);
public String getUser(User user);
public List<User> getListUser();
}
需要在接口头部注明一个“WebService注解”,表示这是一个webservice。
@WebService(endpointInterface = "com.bless.ws.HelloService", serviceName = "HelloService",portName="HelloServicePort")
public class HelloServiceImpl implements HelloService {
@Override
public String sayHi(String text) {
System.out.println("sayHi called...");
return "Hi :" + text;
}
@Override
public String getUser(User user) {
System.out.println("sayUser called...");
return "User:[id=" + user.getId() + "][name=" + user.getName() + "]";
}
@Override
public List<User> getListUser() {
System.out.println("getListUser called...");
List<User> lst = new ArrayList<User>();
lst.add(new User(2, "u2"));
lst.add(new User(3, "u3"));
lst.add(new User(4, "u4"));
lst.add(new User(5, "u5"));
lst.add(new User(6, "u6"));
return lst;
}
}
此时注解WebService内还有三个属性:
endpointInterface表示webservice接口名,因为一个类可以继承多个接口,你必须指明哪个是webservice接口,serviceName表示当前webservice的别名,portName表示当前webservice的端口名,这些属性定义好之后,在wsdl中是能看到的,如果不定义,cxf会配置默认的别名的端口名。
public class Server {
protected Server() throws Exception {
// START SNIPPET: publish
System.out.println("Starting Server");
HelloServiceImpl implementor = new HelloServiceImpl();
String address = "http://localhost:8111/helloWorld";
Endpoint.publish(address, implementor);
// END SNIPPET: publish
}
public static void main(String[] args) throws Exception {
new Server();
System.out.println("Server ready...");
Thread.sleep(5 * 60 * 1000);
System.out.println("Server exiting");
System.exit(0);
}
}
上面这种方式是部署到jetty上的。
3.与spring整合
spring的IOC管理对象非常强大
<?xml version="1.0" encoding="UTF-8"?>
<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/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<jaxws:endpoint id="helloWorld" implementor="com.bless.ws.HelloServiceImpl" address="http://localhost:8080/webservice/helloService" />
<jaxws:client id="helloClient" serviceClass="com.bless.ws.HelloService" address="http://localhost:8080/webservice/helloService" />
</beans>
最后欢迎大家访问我的个人网站:1024s