1.服务接口与实现
(1)接口
如果传入参数需要增加@WebParam注解。
@WebParam注解是必须的,因为java借口编译后的.class文件不保存参数的名字,所以如果没有加注解,参数将被命名为arg0。使用@WebParam注解,以保证xml文件中参数名字的正确性。
package com.hf.framework.service.invoke;
import javax.jws.WebService;
/** * 服务接口 */ @WebService publicinterface InterfaceService {
public String getTime();
} |
(2)实现
@WebService注解让CXF知道我们希望使用哪个接口来创建WSDL。
package com.hf.framework.service.invoke;
import java.text.SimpleDateFormat; import java.util.Date;
import javax.jws.WebService;
/** * 服务接口实现类 */ @WebService(endpointInterface="com.hf.framework.service.invoke.InterfaceService") public class InterfaceServiceImpl implements InterfaceService {
@Override public String getTime() { Date date = new Date(); SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); String datetime = tempDate.format(date); return datetime; }
} |
(3)配置
在web.xml中配置Spring与CXF。(Spring在web.xml中的配置在这里我就不贴出来了。)
<servlet> |
在配置文件app-context-cxf.xml中,配置需要发布的服务。(app-context-cxf.xml文件就是在Spring的配置文件applicationContext.xml引用的。)
<?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"> <importresource="classpath:META-INF/cxf/cxf.xml"/> <importresource="classpath:META-INF/cxf/cxf-extension-soap.xml"/> <importresource="classpath:META-INF/cxf/cxf-servlet.xml"/>
<beanid="interfaceServiceBean"class="com.hf.framework.service.invoke.InterfaceServiceImpl"/>
<!--注意下面的address,这里的address的名称就是访问的WebService的name --> <jaxws:serverid="interfaceService"serviceClass="com.hf.framework.service.invoke.InterfaceService"address="/interfaceService"> <jaxws:serviceBean> <!--配置bean的引用 --> <refbean="interfaceServiceBean"/> </jaxws:serviceBean>
</jaxws:server>
</beans> |
(4)启动
下面启动tomcat服务器后,在浏览器中请求:
http://服务IP:端口/项目名称/服务名称?wsdl
如果你能看到wsdl的xml文件的内容,就说明服务发布成功了。
注意:服务名称指的是app-context-cxf.xml中配置的address。