處理異常:org.springframework.beans.factory.BeanNotOfRequiredTypeException

異常信息:web

Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'baseDao' is expected to be of type [com.web.dao.base.BaseDaoImpl] but was actually of type [com.sun.proxy.$Proxy56]spring

分析處理:編程

   這種狀況通常在使用annotation的方式注入spring的bean出現,因爲spring採用代理的機制致使的。ui

   經過配置織入@Aspectj切面雖然能夠經過編程的方式織入切面,可是通常狀況下,咱們仍是使用spring的配置自動完成建立代理織入切面的工做。經過aop命名空間的聲明自動爲spring容器中那些配置@aspectJ切面的bean建立代理,織入切面。代理

   固然,spring在內部依舊採用AnnotationAwareAspectJAutoProxyCreator進行自動代理的建立工做,但具體實現的細節已經被隱藏起來了有一個proxy-target-class屬性,默認爲false,表示使用jdk動態代理織入加強,當配爲時,表示使用CGLib動態代理技術織入加強。不過即便proxy-target-class設置爲false,若是目標類沒有聲明接口,則spring將自動使用CGLib動態代理。具體請看使用的代碼:對象

代碼1. 使用類注入:接口

@Resource("baseDao")事務

private BaseDaoImpl baseDao;ci

代碼2. 使用接口注入:get

@Resource("baseDao")

private BaseDao baseDao;

代碼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);

        }

    }

相關文章
相關標籤/搜索