1. 程式人生 > >Spring AOP中強制使用CGLIB代理

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.

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)

踩坑點:Spring AOP不支援代理類內部方法呼叫的攔截,比如類中a方法呼叫b方法,切面攔截b方法會失敗的