锁定老帖子 主题:cxf和spring集成的一些事
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2012-03-30
cxf-2.1.3,jdk6,jboss7.0.2,spring3.0.6 用cxf+spring开发web service程序很简单,不过有一些集成问题要注意。在此把这几天发现的一些总结一下,最后有一个遗留的问题 1、关于bean的声明 要发布或者要调用的web service接口,需要用@WebService注解声明。不过要注意的是,@WebService注解不会把类声明为spring的bean 可以声明为bean的方式有以下4个: <jaxws:endpoint> <jaxws:client> <bean id="" class=""> @Component 写了一个类来证明这一点: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:context="http://www.springframework.org/schema/context" 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://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"> <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" /> <context:component-scan base-package="com.huawei.framework" /> <bean id="helloWorldImpl" class="com.huawei.framework.webservice.HelloWorldImpl"> <property name="remedy" ref="remedy" /> </bean> <jaxws:endpoint id="helloWorld" address="/HelloWorld" implementor="#helloWorldImpl" /> <jaxws:client id="remedy" serviceClass="com.huawei.remedy.webservice.RemedyWebServiceCM" address="http://10.78.229.199:8080/remedy/webservice/RemedyWebService" /> </beans> protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = request.getServletContext(); WebApplicationContext wc = WebApplicationContextUtils .getWebApplicationContext(context); String[] beans = wc.getBeanDefinitionNames(); for (String beanName : beans) { System.out.println(beanName); } RemedyWebServiceCM remedy = (RemedyWebServiceCM) wc.getBean("remedy"); AcknowledgeRequest message = new AcknowledgeRequest(); remedy.acknowledge(message); } 在控制台可以看到以下几个bean: 20:02:24,120 INFO [stdout] (http--0.0.0.0-8888-2) helloWorldImpl 20:02:24,120 INFO [stdout] (http--0.0.0.0-8888-2) helloWorld 20:02:24,120 INFO [stdout] (http--0.0.0.0-8888-2) remedy 以上3个bean,就分别是由<bean>、<jaxws:endpoint>、<jaxws:client>生成的 2、如果要在<jaxws:endpoint>的实现类中注入bean的话,要注意: 错误的写法: <jaxws:endpoint id="helloWorld" address="/HelloWorld" implementor="com.huawei.framework.webservice.HelloWorldImpl" /> 用这种写法,虽然HelloWorldImpl类已经被声明成bean了,但是注入是失败的 准确来说,在spring容器中存在有HelloWorldImpl对应的bean,并且相关的依赖也已经注入了。但是cxf框架得到的HelloWorldImpl,与上述的bean不是同一个对象,这个HelloWorldImpl对象可能是用反射或者其他机制创建出来的,没有任何组件被注入 正确的写法: <jaxws:endpoint id="helloWorld" address="/HelloWorld" implementor="#helloWorldImpl" /> 在implementor属性中,用#beanName,这样的话,cxf框架得到的HelloWorldImpl,就是spring容器持有的那个bean。当然这有个前提,就是系统中已经存在这个bean。用<bean id="">或者@Component都是OK的,这里支持注解 3、上面说的是<jaxws:endpoint>,比较简单。但是<jaxws:client>就比较麻烦 我目前感觉,<jaxws:client>声明的bean,没办法在别的bean里用@Autowired注入,只能用<bean id="">的方式来注入 @WebService public interface RemedyWebServiceCM { RemedyResponse acknowledge(AcknowledgeRequest arg0); RemedyResponse close(CloseRequest arg0); RemedyResponse notify(NotifyRequest arg0); } public class HelloWorldImpl implements HelloWorld { private RemedyWebServiceCM remedy; public String sayHi(User theUser) { AcknowledgeRequest message = new AcknowledgeRequest(); remedy.acknowledge(message); return "Hello " + theUser.getName() + " ,your age is " + theUser.getAge(); } public void setRemedy(RemedyWebServiceCM remedy) { this.remedy = remedy; } } <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:context="http://www.springframework.org/schema/context" 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://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"> <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" /> <context:component-scan base-package="com.huawei.framework" /> <bean id="helloWorldImpl" class="com.huawei.framework.webservice.HelloWorldImpl"> <property name="remedy" ref="remedy" /> </bean> <jaxws:endpoint id="helloWorld" address="/HelloWorld" implementor="#helloWorldImpl" /> <jaxws:client id="remedy" serviceClass="com.huawei.remedy.webservice.RemedyWebServiceCM" address="http://10.78.229.199:8080/remedy/webservice/RemedyWebService" /> </beans> 用这种<bean id="">的方式就可以 @Controller public class HelloWorldImpl implements HelloWorld { @Autowired private RemedyWebServiceCM remedy; public String sayHi(User theUser) { AcknowledgeRequest message = new AcknowledgeRequest(); remedy.acknowledge(message); return "Hello " + theUser.getName() + " ,your age is " + theUser.getAge(); } } <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:context="http://www.springframework.org/schema/context" 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://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd"> <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" /> <context:component-scan base-package="com.huawei.framework" /> <jaxws:endpoint id="helloWorld" address="/HelloWorld" implementor="#helloWorldImpl" /> <jaxws:client id="remedy" serviceClass="com.huawei.remedy.webservice.RemedyWebServiceCM" address="http://10.78.229.199:8080/remedy/webservice/RemedyWebService" /> </beans> 用@Autowired加@Component的方式来做,就不行,报以下异常: Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.huawei.remedy.webservice.RemedyWebServiceCM com.huawei.framework.webservice.HelloWorldImpl.remedy; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.huawei.remedy.webservice.RemedyWebServiceCM] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508) [org.springframework.beans-3.0.6.RELEASE.jar:] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84) [org.springframework.beans-3.0.6.RELEASE.jar:] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285) [org.springframework.beans-3.0.6.RELEASE.jar:] ... 21 more Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.huawei.remedy.webservice.RemedyWebServiceCM] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:924) [org.springframework.beans-3.0.6.RELEASE.jar:] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:793) [org.springframework.beans-3.0.6.RELEASE.jar:] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707) [org.springframework.beans-3.0.6.RELEASE.jar:] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480) [org.springframework.beans-3.0.6.RELEASE.jar:] ... 23 more 说自动注入失败,因为找不到RemedyWebServiceCM类型的bean 试了很久,完全搞不定。也想不通是为啥,因为RemedyWebServiceCM这个类型的bean,明明已经用<jaxws:client>声明了,而且用配置文件的方式也是能搞定的 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2012-04-02
你可以从容器中GET出ID为“remedy”的BEAN,看它的类型是什么.
|
|
返回顶楼 | |
发表时间:2012-11-16
楼主,你的问题解决了吗?没有解决的话,主要是你不能用autowired,你必须用resource(name="beanname")这样的形式
|
|
返回顶楼 | |
发表时间:2012-11-18
1、如下代码是由org.apache.cxf.frontend.spring.ClientProxyFactoryBeanDefinitionParser进行解析。
写道
<jaxws:client id="remedy"
serviceClass="com.huawei.remedy.webservice.RemedyWebServiceCM" address="http://10.78.229.199:8080/remedy/webservice/RemedyWebService" />
2、它在解析时使用的是“实例工厂方式”完成创建:http://jinnianshilongnian.iteye.com/blog/1415277
写道
protected Class getFactoryClass()
{ return SpringClientProxyFactoryBean.class; } 写道
bean.setFactoryBean(factoryId, "create");
3、而Bean类型默认指定为
写道
public ClientProxyFactoryBeanDefinitionParser()
{ setBeanClass(Object.class); }
4、 此处注意: <context:component-scan base-package="com.huawei.framework" /> 加载的Bean定义可能早于 <jaxws:client id="remedy" ……>
5、问题所在: 当spring实例化HelloWorldImpl完毕时会使用AutowiredAnnotationBeanPostProcessor完成@Autowired的注入,详见http://jinnianshilongnian.iteye.com/blog/1492424
校验类型是否匹配的代码如下:
public boolean isTypeMatch(String name, Class targetType) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); Class typeToMatch = (targetType != null ? targetType : Object.class);
// Check manually registered singletons. Object beanInstance = getSingleton(beanName, false); //1、此处获取remeby的单例(但remeby此时还没有创建 所以为null) if (beanInstance != null) { if (beanInstance instanceof FactoryBean) { if (!BeanFactoryUtils.isFactoryDereference(name)) { Class type = getTypeForFactoryBean((FactoryBean) beanInstance); return (type != null && typeToMatch.isAssignableFrom(type)); } else { return typeToMatch.isAssignableFrom(beanInstance.getClass()) ; } } else { return !BeanFactoryUtils.isFactoryDereference(name) && typeToMatch.isAssignableFrom(beanInstance.getClass()); } }
else {//2、因此执行此段代码 // No singleton instance found -> check bean definition. BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory -> delegate to parent. return parentBeanFactory.isTypeMatch(originalBeanName(name), targetType); }
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); //2.1、获取Bean定义 Class beanClass = predictBeanType(beanName, mbd, new Class[] {FactoryBean.class, typeToMatch}); //2.2、获取bean类型 if (beanClass == null) { return false; }
// Check bean class whether we're dealing with a FactoryBean. if (FactoryBean.class.isAssignableFrom(beanClass)) { if (!BeanFactoryUtils.isFactoryDereference(name)) { // If it's a FactoryBean, we want to look at what it creates, not the factory class. Class type = getTypeForFactoryBean(beanName, mbd); return (type != null && typeToMatch.isAssignableFrom(type)); } else { return typeToMatch.isAssignableFrom(beanClass); } } else { return !BeanFactoryUtils.isFactoryDereference(name) && typeToMatch.isAssignableFrom(beanClass); } } }
protected Class predictBeanType(String beanName, RootBeanDefinition mbd, Class[] typesToMatch) {//2.2、获取bean类型 Class beanClass = null; if (mbd.getFactoryMethodName() != null) { beanClass = getTypeForFactoryMethod(beanName, mbd, typesToMatch); //2.2.1、因为我们的remeby是通过实例工厂创建,因此调用此段带啊 } else { beanClass = resolveBeanClass(mbd, beanName, typesToMatch); } // Apply SmartInstantiationAwareBeanPostProcessors to predict the // eventual type after a before-instantiation shortcut. if (beanClass != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext(); ) { BeanPostProcessor bp = (BeanPostProcessor) it.next(); if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; Class processedType = ibp.predictBeanType(beanClass, beanName); if (processedType != null) { return processedType; } } } } return beanClass; }
//此方法会遍历所有的工厂方法 查找返回值类型,并且返回该类型 不细说了 (而且我们之前提到的工厂方法create返回值是Object 明显和我们需要的类型不兼容 因此会抛出找不到Bean异常)
protected Class getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd, Class[] typesToMatch) { Class factoryClass = null; boolean isStatic = true;
String factoryBeanName = mbd.getFactoryBeanName(); if (factoryBeanName != null) { if (factoryBeanName.equals(beanName)) { throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, "factory-bean reference points back to the same bean definition"); } // Check declared factory method return type on factory class. factoryClass = getType(factoryBeanName); isStatic = false; } else { // Check declared factory method return type on bean class. factoryClass = resolveBeanClass(mbd, beanName, typesToMatch); }
if (factoryClass == null) { return null; }
// If all factory methods have the same return type, return that type. // Can't clearly figure out exact method due to type converting / autowiring! int minNrOfArgs = mbd.getConstructorArgumentValues().getArgumentCount(); Method[] candidates = ReflectionUtils.getAllDeclaredMethods(factoryClass); Set returnTypes = new HashSet(1); for (int i = 0; i < candidates.length; i++) { Method factoryMethod = candidates[i]; if (Modifier.isStatic(factoryMethod.getModifiers()) == isStatic && factoryMethod.getName().equals(mbd.getFactoryMethodName()) && factoryMethod.getParameterTypes().length >= minNrOfArgs) { returnTypes.add(factoryMethod.getReturnType()); } }
if (returnTypes.size() == 1) { // Clear return type found: all factory methods return same type. return (Class) returnTypes.iterator().next(); } else { // Ambiguous return types found: return null to indicate "not determinable". return null; } }
解决方法: 1、 @DependsOn("remedy") //保证remedy先被加载并初始化 @Component 2、<context:component-scan base-package="com.huawei.framework" /> 放在remedy之后
3、工厂方法返回我们需要的类型RemedyWebServiceCM,而不是Object(这个无法做到 除非我们定义的工厂)
over。
|
|
返回顶楼 | |
发表时间:2012-11-19
龙年,非常感谢!
|
|
返回顶楼 | |
发表时间:2012-11-19
kyfxbl 写道 龙年,非常感谢!
客气哈,确实很细节的问题。你跟踪一遍流程看看,我给的代码也不是很全 只是个大概。 |
|
返回顶楼 | |
发表时间:2012-12-19
jinnianshilongnian 写道
1、如下代码是由org.apache.cxf.frontend.spring.ClientProxyFactoryBeanDefinitionParser进行解析。
写道
<jaxws:client id="remedy"
serviceClass="com.huawei.remedy.webservice.RemedyWebServiceCM" address="http://10.78.229.199:8080/remedy/webservice/RemedyWebService" />
2、它在解析时使用的是“实例工厂方式”完成创建:http://jinnianshilongnian.iteye.com/blog/1415277
写道
protected Class getFactoryClass()
{ return SpringClientProxyFactoryBean.class; } 写道
bean.setFactoryBean(factoryId, "create");
3、而Bean类型默认指定为
写道
public ClientProxyFactoryBeanDefinitionParser()
{ setBeanClass(Object.class); }
4、 此处注意: <context:component-scan base-package="com.huawei.framework" /> 加载的Bean定义可能早于 <jaxws:client id="remedy" ……>
5、问题所在: 当spring实例化HelloWorldImpl完毕时会使用AutowiredAnnotationBeanPostProcessor完成@Autowired的注入,详见http://jinnianshilongnian.iteye.com/blog/1492424
校验类型是否匹配的代码如下:
public boolean isTypeMatch(String name, Class targetType) throws NoSuchBeanDefinitionException { String beanName = transformedBeanName(name); Class typeToMatch = (targetType != null ? targetType : Object.class);
// Check manually registered singletons. Object beanInstance = getSingleton(beanName, false); //1、此处获取remeby的单例(但remeby此时还没有创建 所以为null) if (beanInstance != null) { if (beanInstance instanceof FactoryBean) { if (!BeanFactoryUtils.isFactoryDereference(name)) { Class type = getTypeForFactoryBean((FactoryBean) beanInstance); return (type != null && typeToMatch.isAssignableFrom(type)); } else { return typeToMatch.isAssignableFrom(beanInstance.getClass()) ; } } else { return !BeanFactoryUtils.isFactoryDereference(name) && typeToMatch.isAssignableFrom(beanInstance.getClass()); } }
else {//2、因此执行此段代码 // No singleton instance found -> check bean definition. BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory -> delegate to parent. return parentBeanFactory.isTypeMatch(originalBeanName(name), targetType); }
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); //2.1、获取Bean定义 Class beanClass = predictBeanType(beanName, mbd, new Class[] {FactoryBean.class, typeToMatch}); //2.2、获取bean类型 if (beanClass == null) { return false; }
// Check bean class whether we're dealing with a FactoryBean. if (FactoryBean.class.isAssignableFrom(beanClass)) { if (!BeanFactoryUtils.isFactoryDereference(name)) { // If it's a FactoryBean, we want to look at what it creates, not the factory class. Class type = getTypeForFactoryBean(beanName, mbd); return (type != null && typeToMatch.isAssignableFrom(type)); } else { return typeToMatch.isAssignableFrom(beanClass); } } else { return !BeanFactoryUtils.isFactoryDereference(name) && typeToMatch.isAssignableFrom(beanClass); } } }
protected Class predictBeanType(String beanName, RootBeanDefinition mbd, Class[] typesToMatch) {//2.2、获取bean类型 Class beanClass = null; if (mbd.getFactoryMethodName() != null) { beanClass = getTypeForFactoryMethod(beanName, mbd, typesToMatch); //2.2.1、因为我们的remeby是通过实例工厂创建,因此调用此段带啊 } else { beanClass = resolveBeanClass(mbd, beanName, typesToMatch); } // Apply SmartInstantiationAwareBeanPostProcessors to predict the // eventual type after a before-instantiation shortcut. if (beanClass != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext(); ) { BeanPostProcessor bp = (BeanPostProcessor) it.next(); if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; Class processedType = ibp.predictBeanType(beanClass, beanName); if (processedType != null) { return processedType; } } } } return beanClass; }
//此方法会遍历所有的工厂方法 查找返回值类型,并且返回该类型 不细说了 (而且我们之前提到的工厂方法create返回值是Object 明显和我们需要的类型不兼容 因此会抛出找不到Bean异常)
protected Class getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd, Class[] typesToMatch) { Class factoryClass = null; boolean isStatic = true;
String factoryBeanName = mbd.getFactoryBeanName(); if (factoryBeanName != null) { if (factoryBeanName.equals(beanName)) { throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName, "factory-bean reference points back to the same bean definition"); } // Check declared factory method return type on factory class. factoryClass = getType(factoryBeanName); isStatic = false; } else { // Check declared factory method return type on bean class. factoryClass = resolveBeanClass(mbd, beanName, typesToMatch); }
if (factoryClass == null) { return null; }
// If all factory methods have the same return type, return that type. // Can't clearly figure out exact method due to type converting / autowiring! int minNrOfArgs = mbd.getConstructorArgumentValues().getArgumentCount(); Method[] candidates = ReflectionUtils.getAllDeclaredMethods(factoryClass); Set returnTypes = new HashSet(1); for (int i = 0; i < candidates.length; i++) { Method factoryMethod = candidates[i]; if (Modifier.isStatic(factoryMethod.getModifiers()) == isStatic && factoryMethod.getName().equals(mbd.getFactoryMethodName()) && factoryMethod.getParameterTypes().length >= minNrOfArgs) { returnTypes.add(factoryMethod.getReturnType()); } }
if (returnTypes.size() == 1) { // Clear return type found: all factory methods return same type. return (Class) returnTypes.iterator().next(); } else { // Ambiguous return types found: return null to indicate "not determinable". return null; } }
解决方法: 1、 @DependsOn("remedy") //保证remedy先被加载并初始化 @Component 2、<context:component-scan base-package="com.huawei.framework" /> 放在remedy之后
3、工厂方法返回我们需要的类型RemedyWebServiceCM,而不是Object(这个无法做到 除非我们定义的工厂)
over。
大牛人,给力
|
|
返回顶楼 | |
浏览 26948 次