Spring AOP中强制使用CGLIB代理

spring官方文档中关于aop的描述如下:

Spring AOP defaults to using standard JDK dynamic proxies for AOP proxies. This enables any interface (or set of interfaces) to be proxied.

Spring AOP can also use CGLIB proxies. This is necessary to proxy classes rather than interfaces. CGLIB is used by default if a business object does not implement an interface. As it is good practice to program to interfaces rather than classes; business classes normally will implement one or more business interfaces. It is possible to force the use of CGLIB, in those (hopefully rare) cases where you need to advise a method that is not declared on an interface, or where you need to pass a proxied object to a method as a concrete type.

(来源:http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/aop.html)

xml配置

<aop:aspectj-autoproxy proxy-target-class="true"/>

注解配置

在Springboot中使用过注解配置方式的人会问是否需要在程序主类中增加@EnableAspectJAutoProxy来启用,实际并不需要。看下面关于AOP的默认配置属性,其中spring.aop.auto属性默认是开启的,也就是说只要引入了AOP依赖后,其实默认已经增加了@EnableAspectJAutoProxy

# AOP
spring.aop.auto=true # Add @EnableAspectJAutoProxy.
spring.aop.proxy-target-class=false # Whether subclass-based (CGLIB) proxies are to be created (true) as opposed to standard Java interface-based proxies (false).

当我们需要强制使用CGLIB来实现AOP的时候,需要配置spring.aop.proxy-target-class=true@EnableAspectJAutoProxy(proxyTargetClass = true)

参考:http://blog.didispace.com/springbootaoplog/

踩坑点:Spring AOP不支持代理类内部方法调用的拦截,比如类中a方法调用b方法,切面拦截b方法会失败的

参见:http://blog.csdn.net/quzishen/article/details/5803721

你可能感兴趣的:(java,spring)