使用時的問題" type="hidden"/>

使用時的問題


在測試springAOP時,我的測試方法中獲取bean時報錯:

ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = app.getBean(AccountServiceImpl.class);//此處是通過AccountService接口的實現類來獲取bean。結果報錯了:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'cn.xx.service.impl.AccountServiceImpl' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:347)
說找不到cn.xx.service.impl.AccountServiceImpl這個類。

查了一下spring的配置文件applicationContext.xml,發現里面少了一句<aop:aspectj-autoproxy/>配置。但是加上之后仍然報錯。這是為什么呢。

再查看這個標簽有一個屬性:proxy-target-class,它的值有false(默認)和true。再將它設置成true之后,結果運行成功了。總結一下原因如下:

 <aop:aspectj-autoproxy proxy-target-class="false"/> 基於接口,使用JDK動態代理

JDK Dynamic proxy can only proxy by interface (so your target class needs to implement an interface, which will also be implemented by the proxy class).

 

<aop:aspectj-autoproxy proxy-target-class="true"/> 基於類,需要使用cglib庫

CGLIB (and javassist) can create a proxy by subclassing. In this scenario the proxy becomes a subclass of the target class. No need for interfaces.

測試代碼中是從過實現類來獲取容器中對象,則需要使用cglib庫,所以在proxy-target-class="false"時會報錯。

 

如果將測試代碼中改為通過AccountService.class(接口)來獲取bean.也可以正確運行。

 

學習過程中碰到的問題,順便記錄。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM