---
title: "CXF和spring整合实现webservice实例"
author: "tsinglongwu"
date: "2010-12-03T15:51:55Z"
tags: ["Java", "Spring", "WebService", "XML", "应用服务器"]
categories: ["企业架构"]
slug: "cxf-spring-webservice"
draft: false
lastmod: "2010-12-03T15:55:09Z"
id: 832704
url: "https://tsinglongwu.iteye.com/blog/832704"
---

环境：JDK6.0，cxf-2.0.7，spring2.5，tomcat6.0 \[b]\[color=red]服务器端\[/color]\[/b]： 1.新建Web项目，例如webws，导入cxf-2.0.7/lib下的jar包和spring2.5的包，因为cxf支持spring，因此它自带有sping的一些核心包，为了以后扩展，保险起见都一起导入吧。。 2.新建一个服务接口IHelloWorld.java，该接口是面向客户端，暴露服务： \[code="java"]package cn.com.service; import javax.jws.WebParam; import javax.jws.WebService; @WebService public interface IHelloWorld { //@WebParam(name="arg0")可有可无，为了增强可读性 public String sayHello(@WebParam(name="arg0")String text); }\[/code] 3.再新建该接口的实现类HelloWorldImpl.java： \[code="java"]package cn.com.service; import javax.jws.WebService; @WebService(endpointInterface="cn.com.service.IHelloWorld") public class HelloWorldImpl implements IHelloWorld { public String sayHello(String text) { return "Hello" + text ; } }\[/code] 4.现在可以进行spring配置了，在eclipse的src文件夹下新建applicationContext.xml： \[code="xml"] \[/code] 注意：1).元素里面的命名空间一定要正确，特别要增加xmlns:jaxws="http://cxf.apache.org/jaxws"，http://cxf.apache.org/jaxws，http://cxf.apache.org/schemas/jaxws.xsd； 2).cxf.xml，cxf-extension-soap.xml，cxf-servlet.xml三个文件都在cxf-2.0.7.jar中把它们拷贝到META-INF/目录下。 5.配置web.xml： \[code="java"] contextConfigLocation classpath:applicationContext.xml org.springframework.web.context.ContextLoaderListener CXFServlet CXF Servlet org.apache.cxf.transport.servlet.CXFServlet 1 CXFServlet /* index.jsp \[/code] 到此服务器端基本上告一段落，可以将应用部署到tomcat，启动并访问http://localhost:8080/webws/HelloWorld?wsdl，如果能正确显示xml文件则说明部署成功。 \[b]\[color=red]客户端\[/color]\[/b]： 1.新建一个java项目，例如wsclient，也导入cxf-2.0.7和spring包 2.新建客户程序（如果熟悉cxf可以运用cxf的wsdl2java命令直接根据wsdl生成），如Test.java: \[code="java"] package pro.webws.client; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { public static void main(String\[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-client.xml"); IHelloWorld client = (IHelloWorld) ctx.getBean("client"); String result = client.sayHello("你好!"); System.out.println(result); } }\[/code] 根据代码，我们知道还需要新建一个IHelloWorld接口，这是服务器端暴露的服务，我们还需要在客户端再新建一个以利用之，代码和服务器端一致即可，不再赘述。 现在可以配置客户端的spring文件了，新建spring-client.xml文件： \[code="java"] \[/code] 注意：中的/HelloWorld要与服务器端applicationContext.xml中的的address属性对应。 现在服务器和客户端都已完成，启动tomcat，运行客户程序，将输出结果： Hello你好!