Spring AOP (Aspect-Oriented Programming) is a powerful tool that allows developers to implement cross-cutting concerns in their applications without having to modify the source code of the application classes directly. The main concept behind Spring AOP is to use a combination of Aspect and Advices to implement cross-cutting concerns in the application without modifying its core logic. In this answer, we’ll discuss the internals of Spring AOP and how it creates proxy objects for implementing cross-cutting concerns.
When a Spring AOP-based application is executed, Spring creates proxy objects for the application’s classes. These proxy objects are used to apply cross-cutting concerns to the application, while leaving the original application classes untouched. The proxy objects are created based on the configured AOP aspects and advice.
Internally, Spring uses a special proxy object known as a "dynamic proxy" to implement the AOP features. Dynamic proxies are created at runtime by implementing the interfaces of the classes that they’re proxying. The dynamic proxy intercepts method calls on the class it’s proxying and delegates those calls to the appropriate advice classes based on the pointcut configured in the AOP aspect.
There are two types of proxies that Spring AOP uses - JDK Dynamic Proxies and CGLIB proxies.
JDK Dynamic Proxies are used when the target class being proxied implements one or more interfaces. In JDK Dynamic Proxy-based AOP, Spring creates a proxy object that implements the interfaces of the target class and then delegates the method calls to the appropriate advice classes based on the pointcut configured in the AOP aspect.
CGLIB proxies are used when the target class being proxied does not implement any interfaces. In CGLIB Proxy-based AOP, Spring creates a subclass of the target class and then delegates the method calls to the appropriate advice classes based on the pointcut configured in the AOP aspect.
To summarize, Spring AOP uses proxy objects to implement cross-cutting concerns in an application. These proxies are created at runtime using either JDK Dynamic Proxy or CGLIB Proxy. The dynamic proxy intercepts method calls on the class it’s proxying and delegates those calls to the appropriate advice classes based on the pointcut configured in the AOP aspect. This allows developers to add cross-cutting concerns to their applications without having to modify the original application classes.