CXF 和 Spring 版本问题
CXF和Spring结合的非常紧密,默认发布Server端是需要用到Spring的,但是项目中用到的Spring jar包比较老2.0,CXF版本2.3.1,跟Spring不兼容,需要换乘Spring2.5,但是换jar包对原来的项目存在风险,上网搜了一个脱离Spring运行的方法。
?
写一个类继承CXFNonSpringServlet,重写loadBus方法。
@SuppressWarnings("unchecked")public void loadBus(ServletConfig servletConfig) throws ServletException {super.loadBus(servletConfig);Bus bus = this.getBus();BusFactory.setDefaultBus(bus);Enumeration<String> enums = getInitParameterNames();while (enums.hasMoreElements()) {String key = enums.nextElement();String value = getInitParameter(key);try {Class clz = Class.forName(value);try {Endpoint.publish(key, clz.newInstance());} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}} catch (ClassNotFoundException e) {e.printStackTrace();}}}
?
在web.xml里将要发布的类配置一下,可以配置多个。
<servlet> <servlet-name>CXFServlet</servlet-name> <servlet-class> com.infodms.ws.util.MyCXFNoSpringServlet </servlet-class> <init-param> <param-name>/TestService</param-name> <param-value>com.infodms.ws.test.TestServiceImpl</param-value> </init-param> <init-param> <param-name>/HelloWorld</param-name> <param-value>com.infodms.ws.test.HelloWorldImpl</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>CXFServlet</servlet-name> <url-pattern>/ws/*</url-pattern> </servlet-mapping>
?
配置完成,启动tomcat,报错,还是加载了spring,但是代码确实走了刚刚加的MyCXFNoSpringServlet
java.lang.RuntimeException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.apache.cxf.bus.spring.BusApplicationListener' defined in class path resource [META-INF/cxf/cxf.xml]: Initialization of bean failed; nested exception is java.lang.NoSuchMethodError: org.springframework.context.support.AbstractApplicationContext.addApplicationListener(Lorg/springframework/context/ApplicationListener;)Vorg.apache.cxf.bus.spring.SpringBusFactory.createBus(SpringBusFactory.java:96)
?调试了一下源码,内部需要从环境变量中取得org.apache.cxf.bus.factory的值,如果为空就默认按照spring的方式加载。于是在类的最开始加入一行代码。
System.setProperty("org.apache.cxf.bus.factory", "org.apache.cxf.bus.CXFBusFactory");
?
再次启动tomcat,报错,由异常可知WoodstoxValidationImpl类没有默认构造方法,通过反射实例化对象报错,看了一下这个类的源码,确实没有无参构造方法。
Caused by: java.lang.InstantiationException: org.apache.cxf.wstx_msv_validation.WoodstoxValidationImpl at java.lang.Class.newInstance0(Class.java:340) at java.lang.Class.newInstance(Class.java:308) at org.apache.cxf.bus.extension.Extension.load(Extension.java:110)
?
http://cxf.547215.n5.nabble.com/jira-Created-CXF-3077-java-lang-InstantiationException-org-apache-cxf-wstx-msv-validation-WoodstoxVal-td3228305.html
引用这个,加入三个jar包
woodstox-core-asl-4.0.8.jar?
stax2-api-3.0.2.jar
msv.jar
?
问题解决。