Anand
Anand

Reputation: 21320

Why protected methods are not intercepted by Spring AOP

I am familiar with Spring AOP. As i read in the spring documentation http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/aop.html, Spring AOP works on the concept of proxies.

In the section 8.2.3.1 Supported Pointcut Designators, i found the below note

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!

At first, I didn't believe it, so i tried to implement it without using interfaces where all methods are public by default and was surprised that the above is true. Since proxy classes are subclasses of the advised/target object and protected methods can be accessed by a subclass so I thought protected methods would work fine.

Can someone please let me know why protected methods are not intercepted? Am I missing something?

Upvotes: 9

Views: 3810

Answers (2)

elmehdi
elmehdi

Reputation: 479

In fact in last spring documentation it is clearly that is possible using cglib

Due to the proxy-based nature of Spring’s AOP framework, calls within the target object are by definition not intercepted. For JDK proxies, only public interface method calls on the proxy can be intercepted. With CGLIB, public and protected method calls on the proxy will be intercepted, and even package-visible methods if necessary. However, common interactions through proxies should always be designed through public signatures.

As they mention public and package-visible are included within use of cglib, try to use latests spring version, they could update such things accordingly

check here

Upvotes: 4

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

JDK proxies are based on interfaces and this means that all implemented methods will be public

Upvotes: 5

Related Questions