解决: org.springframework.beans.factory.BeanNotOfRequiredTypeException办法

原因

在使用annotation的方式注入spring的bean 出现的,具体是由于spring采用代理的机制导致的,代码如下:

//使用类注入:

@Resource(name = "systemCallServiceImpl")  

private SystemCallServiceImplsystemCallServiceImpl; 

//使用接口注入:

@Resource(name = "systemCallServiceImpl")  

private ISystemCallService systemCallServiceImpl;

 

代码1不能使用JDK的动态代理注入,原因是JDK的动态代理不支持类注入,只支持接口方式注入;

代码2可以使用JDK动态代理注入;

如果要使用代码1的方式,必须使用cglib代理;

推荐使用代码2的方式,基于接口编程的方式!

Spring动态代理

//1.使用aop配置:   
    <aop:config proxy-target-class="false"> </aop:config>    
//2. aspectj配置:   
    <aop:aspectj-autoproxy proxy-target-class="true"/>        
//3. 事务annotation配置:   
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>  
//3种配置,只要使用一种即可,设置proxy-target-class为true即使用cglib的方式代理对象。

 

 

JDK代理和cglib代理判断

//org.springframework.aop.framework.DefaultAopProxyFactory     

  

//参数AdvisedSupport 是Spring AOP配置相关类     

  

public AopProxy createAopProxy(AdvisedSupport advisedSupport)     

  

        throws AopConfigException {     

  

    //在此判断使用JDK动态代理还是CGLIB代理     

  

    if (advisedSupport.isOptimize() || advisedSupport.isProxyTargetClass()     

  

            || hasNoUserSuppliedProxyInterfaces(advisedSupport)) {     

  

        if (!cglibAvailable) {     

  

            throw new AopConfigException(     

  

                    "Cannot proxy target class because CGLIB2 is not available. "    

  

                            + "Add CGLIB to the class path or specify proxy interfaces.");     

  

        }     

  

        return CglibProxyFactory.createCglibProxy(advisedSupport);     

  

    } else {     

  

        return new JdkDynamicAopProxy(advisedSupport);     

  

    }     

  

}

 

参考:http://ekisstherain.iteye.com/blog/1569236

 

发表评论

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据