您的位置:首页 > 编程语言 > Java开发

【知识库】--spring aop 动态代理--inner private protected 方法失效(212)

2017-05-27 21:12 393 查看
私有方法或者保护的方法无效!

AspectJ pointcut for annotated PRIVATE methods

Due to the proxy-based nature of Spring's AOP framework, protected methods are by definition not intercepted,

neither for JDK proxies (where this isn't applicable) nor for CGLIB proxies (where this is technically possible

but not recommendable for AOP purposes). As a consequence, any given pointcut will be matched against public methods only!

If your interception needs include protected/private methods or even constructors, consider the use of Spring-driven native 

AspectJ weaving instead of Spring's proxy-based AOP framework. This constitutes a different mode of AOP usage with different 
characteristics, so be sure to make yourself familiar with weaving first before making a decision.

下文解释:

Spring AOP使用JDK动态代理或者CGLIB来为目标对象创建代理。(建议优先使用JDK的动态代理)

如果被代理的目标对象实现了至少一个接口,则会使用JDK动态代理。所有该目标类型实现的接口都将被代理。 若该目标对象没有实现任何接口,则创建一个CGLIB代理。

如果你希望强制使用CGLIB代理,(例如:希望代理目标对象的所有方法,而不只是实现自接口的方法) 那也可以。但是需要考虑以下问题: 

无法通知(advise)final方法,因为他们不能被覆写。

代理对象的构造器会被调用两次。因为在CGLIB代理模式下每一个代理对象都会 产生一个子类。每一个代理实例会生成两个对象:实际代理对象和它的一个实现了通知的子类实例 而是用JDK代理时不会出现这样的行为。通常情况下,调用代理类型的构造器两次并不是问题, 因为除了会发生指派外没有任何真正的逻辑被实现。
且CGLib的效率没有使用JDK代理机制高,速度平均要慢8倍左右。

强制使用CGLIB代理需要将<aop:config>的proxy-target-class属性设为true:

<aop:config proxy-target-class="true">

</aop:config>

当使用@AspectJ自动代理时要强制使用CGLIB,请将<aop:aspectj-autoproxy>的proxy-target-class属性设置为true:

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


 inner public方法无效

原因其实就是一句话:Spring AOP是基于代理机制的.

具体文档参考:
http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/aop.html#aop-introduction-spring-defn
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: