<aop:aspectj-autoproxy proxy-target-class="false|true"/>使用时的问题

在测试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.也可以正确运行。

学习过程中碰到的问题,顺便记录。

原文地址:https://www.cnblogs.com/xiaoxionganna/p/9329727.html