在项目的 src 目录中新建一个 ws.cxf 包,并在里面创建接口类 ISurveyService.Java,为了简单示示例起见,我们仅创建一个方法 public String vote(String username,int point); 这里要注意的是我们在接口上用 @WebService 注解标明这是一个即将暴露为 Web Service 的接口,并将里面的方法都暴露出去。完整的接口代码清单如下:
- package ws.cxf;
- import javax.jws.WebService;
- @WebService
- public interface ISurveyService
- {
- /**
- * @param username 名字
- * @param point 分数
- * @return
- */
- public String vote(String username,int point);
- }
接下来,我们根据接口的定义,来实现它。
具体类实现
针对接口的定义,我们创建一个相应的实现类,并将其定义在 sw.cxf.impl 包中,完整的代码清单如下:
- package ws.cxf.impl;
- import javax.jws.WebService;
- import ws.cxf.ISurveyService;
- @WebService
- public class SurveyService implements ISurveyService
- {
- private String excludeName = "Michael";
- private int leastPonit = 5;
- public String vote(String username,int point)
- {
- String result = "";
- if(excludeName.equals(username))
- {
- result = " 您不能重复进行投票!";
- }
- else
- {
- result = " 谢谢您的投票!";
- if(point < leastPonit)
- {
- result += " 您的投票分数太低!";
- }
- else
- {
- result += " 您的投票分数通过审核!";
- }
- }
- return result;
- }
- // For IoC
- public String getExcludeName()
- {
- return excludeName;
- }
- public void setExcludeName(String excludeName)
- {
- this.excludeName = excludeName;
- }
- public int getLeastPonit()
- {
- return leastPonit;
- }
- public void setLeastPonit(int leastPonit)
- {
- this.leastPonit = leastPonit;
- }
- }
接口定义与具体的实现就这样简单完成了,接下来就是相关的配置工作了,首先进行 Spring 的 Bean 配置。
Spring 配置
在 src 目录中创建 beanRefServer.xml 文件,用来定义 Spring 的 Bean 的配置,CXF 支持 Spring 2.0 Schema 标签配置方式,并且提供快捷暴露 Web Services 的标签。
首先,我们需要引入 Spring 与 CXF 的命名空间(namespace),如下:
- <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-2.0.xsd
- http://cxf.apache.org/jaxws
- http://cxf.apache.org/schemas/jaxws.xsd">
这样,我们可以使用 Spring 与 CXF 的标签配置了。接着,我们需要引入我们所需要的 CXF 的 Bean 定义文件,如下:
- <!-- Import Apache CXF Bean Definition -->
- <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"/>
