How is Java AOP implemented?
Aspect-Oriented Programming (AOP) in Java is implemented using the proxy pattern. In AOP, a proxy object can be created to intercept and handle method calls on the target object. The proxy object can insert additional code at specific times, such as before or after a method is executed, or when an exception is thrown, to separate cross-cutting concerns.
In Java, there are two ways to implement AOP.
- Static proxy: Implementing AOP by manually creating a proxy class. The proxy class must implement the same interface as the target object and add additional logic within the proxy class. Before and after calling the target object’s method, execute the additional logic by calling the proxy class’s method.
- Dynamic proxy: Implementing AOP using Java’s dynamic proxy mechanism. Dynamic proxy utilizes Java’s reflection mechanism to dynamically generate proxy classes at runtime. These proxy classes are generated at runtime without the need for manual coding. By specifying a target object and interceptors, a proxy object can be generated at runtime to intercept method calls on the target object and execute code in the interceptor at specific times.
In the Spring framework, AOP is commonly implemented using dynamic proxy. Spring utilizes two methods, JDK dynamic proxy and CGLIB dynamic proxy, to generate proxy objects. If the target object implements an interface, Spring will use JDK dynamic proxy to generate the proxy object. If the target object does not implement an interface, Spring will use CGLIB dynamic proxy to generate the proxy object.