zoukankan      html  css  js  c++  java
  • 代理及注入之org.springframework.beans.factory.BeanNotOfRequiredTypeException (转载)

    错误信息:

        org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'aisleService' must be of type [com.gdie.whlocation.service.impl.AisleService], but was actually of type [$Proxy38]

        这个问题出现的原因:一般在使用annotation的方式注入spring的bean 出现的,具体是由于spring采用代理的机制导致的,Spring使用JDK的动态代理注入,jdk的动态代理不支持类注入,只支持接口方式注入

    看使用的代码:

        1. 使用类注入:  
        @Resource(name = "aisleService")  
        private AisleServiceImpl aisleService;  
          
        2. 使用接口注入:  
        @Resource(name = "aisleService")  
        private IAisleService aisleService;  

    代码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的方式代理对象。

     附:spring的aop代理判断逻辑:

        //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);     
          
            }     
          
        }  
  • 相关阅读:
    expect详解及自动登录脚本的实现
    NFS服务端+客户端配置
    交互式shell脚本对话框----whiptail指令
    自定制Centos7.3系统镜像(ISO)
    云原生简述
    Linux下修改MTU(最大传输单元)
    MySQL-5.7组提交(Group Commit)原理
    AWS putty终端ssh密钥登陆方法
    一个简单的从web页面获取数据插入数据库的小程序
    新建一个简单的Java web前后台交互小程序时报错:java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SqlServerDriver
  • 原文地址:https://www.cnblogs.com/lige-H/p/7200177.html
Copyright © 2011-2022 走看看