Spring AOP
June 21, 2020

M02 Q03 How does Spring solve (implement) a cross-cutting concern?

Spring Implements cross-cutting concerns with the usage of Spring AOP module. Spring AOP uses AspectJ expression syntax for Pointcut expressions, which are matched against Join Point, code is altered with logic implemented in advices. In Spring AOP Joint Point is always method invocation.

Spring AOP uses Runtime Weaving, and for each type subject to aspects, to intercepts calls, spring creates one type of proxy:

  • JDK Proxy – created for classes that implement an interface
  • CGLIB Proxy – created for a class that is not implementing any interface. It is possible to force Spring to use CGLIB Proxy with the usage of @EnableAspectJAutoProxy(proxyTargetClass = true)

JDK Proxy

JDK Proxy is used when the class implements at least one interface.

In this way, Spring creates a third class which is generated dynamically. And this class is used by your client code.

Client code firstly invoking a Proxy class. The proxy class analyzes if there is before or after section or around advice and executes advice first before the original code.

CGLIB Proxy

When we have a class that does not have any interface Spring uses CGLIB Proxy.

CGLIB Proxy creates a dynamic proxy class that extends the original class. All of the methods are overridden.

And your client code is invoking Proxy, not the original class.

It is possible to force Spring to use CGLIB Proxy with the usage of @EnableAspectJAutoProxy(proxyTargetClass = true)