1、在web.xml中加入CXFServlet:
<!-- 下面表示所有来自/cxfservice/*的请求,都交给 CXFServlet来处理 。-->
<servlet>
<servlet-name>cxf</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cxf</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
2、在spring的配置文件中导入cxf的配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd">
<context:annotation-config /> <!-- 对属性文件 -->
<context:component-scan base-package="cn" />
<bean id="userService" class="cn.tdtk.ws.dao.impl.UserServiceImpl"/>
<bean id="helloWorldImpl" class="cn.tdtk.ws.dao.impl.HelloWorldImpl">
<property name="us" ref="userService"/>
</bean>
<!-- web应用的类加载路径有两类:
1. WEB-INF/classes 目录。
2. 加载WEB-INF/lib 目录下的cxf的jar文件中的META-INF下的文件。-->
<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"/>
<!-- implementor指定webservice的服务提供者,有两种表示形式:
1. 通过已知服务器的类名(implementor="cn.tdtk.ws.dao.impl.HelloWorldImpl")。
2. 设置为容器中的一个Bean (implementor="#helloWorldImpl").
-->
<jaxws:endpoint
implementor="#helloWorldImpl"
address="/helloService">
<!-- 添加in拦截器 -->
<jaxws:inInterceptors>
<bean class="org.apache.cxf.interceptor.LoggingInInterceptor"/>
<!-- <bean class="cn.tdtk.ws.interceptor.AuthInterceptor"/> -->
</jaxws:inInterceptors>
</jaxws:endpoint>
</beans>
3、调用spring的webservice:
将webservice生成java文件:
测试代码:
public class ClientMain {
/**
* @param args
*/
public static void main(String[] args) {
HelloWorldImplService factory= new HelloWorldImplService();
HelloWorld hw = factory.getHelloWorldImplPort();
String s = hw.sayHello("tom");
System.out.println(s);
}
4、通过依赖注入将业务层注入到webservice中:
public class HelloWorldImpl implements HelloWorld {
private UserService us;
@Override
public String sayHello(String name) {
return name + ",你好,现在的时间是: "+new Date();
}
@Override
public List<Cat> getCatsByUser(User user) {
// 在这里只是调用业务逻辑组件,而不实现,具体的实现由业务类去完成
return us.getCatsByUser(user);
}
@Override
public Map<String, Cat> getAllCats() {
return us.getAllCats();
}
public void setUs(UserService us) {
this.us = us;
}
}