Spring AOP (Cutting-Oriented Programming)
The following content was generated by ChatGPT
AOP (Aspect-Oriented Programming)is a programming paradigm designed to increase program modularity by separating concerns.Spring AOP is primarily used for implementations that cut across concerns (such as logging, security, transaction management, etc.). In Spring, the main function of AOP is to enhance functionality for beans, such as adding additional behavior.
1. Static versus dynamic agents
static proxyrespond in singingdynamic agentare the two main ways to implement AOP.
static proxy:
- The target class of the proxy is known at compile time and the proxy class is explicitly defined in the code.
- The disadvantage of static proxies is that you need to manually write proxy classes for each proxied class, resulting in redundant and difficult to maintain code.
dynamic agent:
- Dynamic proxies generate proxy classes at runtime. There are two ways to implement dynamic proxies in Java:JDK Dynamic Agentscap (a poem)CGLIB。
- The advantage of dynamic proxies is that they can be generated for any interface without having to manually write a proxy class.
JDK Dynamic Agents
-
JDK Dynamic AgentsProxies only classes that implement the interface. It passes the
class and
Interface Implementation.
-
InvocationHandler
interface is defined in theinvoke
method, which is executed when the proxy object calls the method.
import ;
import ;
import ;
public class JdkProxyExample {
public static void main(String[] args) {
Foo foo = new FooImpl();
Foo proxyFoo = (Foo) (
(),
new Class<?>[]{},
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Front Enhancement
("Before method: " + ());
Object result = (foo, args);
// rear enhancement
("After method: " + ());
return result;
}
});
();
}
}
interface Foo {
void doSomething();
}
class FooImpl implements Foo {
public void doSomething() {
("Doing something...");
}
}
CGLIB Dynamic Proxy
- CGLIB Dynamic ProxyProxies are implemented by generating subclasses of the target class, so that classes without interfaces can be proxied.CGLIB uses the ASM bytecode manipulation library to generate proxy classes.
- CGLIB's proxy class overrides the methods of the target class by calling the parent class's
super
method to implement a call to the target method.
import ;
import ;
import ;
public class CglibProxyExample {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
();
(new MethodInterceptor() {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
// Front Enhancement
("Before method: " + ());
Object result = (obj, args);
// rear enhancement
("After method: " + ());
return result;
}
});
Foo fooProxy = (Foo) ();
();
}
}
class Foo {
public void doSomething() {
("Doing something...");
}
}
2. Spring AOP implementation principle
Spring AOP SupportJDK Dynamic Agentsrespond in singingCGLIB Two proxy mechanisms.
- JDK Dynamic Agents: When the target class implements one or more interfaces, Spring uses the JDK Dynamic Proxy by default to create a proxy object for the target class.
- CGLIB: If the target class does not implement any interfaces, Spring uses CGLIB to generate a proxy for the target class.
Spring UsageAopProxy
Interface and its two implementation classesJdkDynamicAopProxy
cap (a poem)CglibAopProxy
to handle these two proxy mechanisms separately.
Bean is wrapped in a Proxy
- When the Spring container starts, it parses configuration files or annotations to generate bean definition information.
- After the bean is initialized, Spring AOP's
BeanPostProcessor
one of the following (e.g.AbstractAutoProxyCreator
subclasses) will check to see if the bean needs AOP enhancements. - If enhancements are needed, a proxy object is generated to replace the original bean.This process is accomplished by calling the
getProxy()
method to accomplish this.
Creating a Proxy Object
AopProxy
interface defines thegetProxy()
Methods:
-
JdkDynamicAopProxy
: Dynamically proxied via the JDK()
method creates the proxy object. -
CglibAopProxy
: via CGLIB'sEnhancer
class to create proxy objects.
Getting Proxy Objects
getProxy()
method returns the proxy object. The proxy object is created by calling thegetProxy()
method is dynamically generated and all AOP enhancement logic is handled in this method.
InvocationHandler implementation
In the JDK dynamic agent, theInvocationHandler
(used form a nominal expression)invoke()
method contains the logic for the interceptor chain.CglibAopProxy
pass (a bill or inspection etc)Callback
cap (a poem)MethodInterceptor
Implement similar functionality.
public class MyInvocationHandler implements InvocationHandler {
private final Object target;
public MyInvocationHandler(Object target) {
= target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// pretreatment
("Before method: " + ());
// Calling the methods of the target object
Object result = (target, args);
// post-processing
("After method: " + ());
return result;
}
}
existinvoke()
Methods in:
- Performs front-end enhancement logic.
- Use reflection to invoke the methods of the target object.
- Performs post enhancement logic.
3. Interceptor chaining and method chaining enforcement
Interceptor chains in Spring AOP are formed by theAdvisor
respond in singingMethodInterceptor
Composition.Advisor
Contains a cut point (Pointcut) and notification (Advice), the cut point defines which methods need to be intercepted, and the notification defines the logic that will be executed at the time of interception.
when the proxy object invokes the method:
-
AopProxy
The call chain invokes the interceptors in the interceptor chain in turn. - Interceptor chaining handles each interceptor through the chain of responsibility pattern.
- If one of the interceptors in the interceptor chain decides to execute the target method, it calls the
()
Methods.
public class MyMethodInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
// pretreatment
("Before method: " + ().getName());
// Calling the methods of the target object
Object result = ();
// post-processing
("After method: " + ().getName());
return result;
}
}
existinvoke()
method.proceed()
method is used to proceed to the next interceptor or target method. If there are no other interceptors, the target method is executed.
summarize
Spring AOP uses the proxy pattern to realize the management of cross-cutting concerns, mainly through the JDK dynamic proxy and CGLIB dynamic proxy implementation. Proxy objects are passed through theAopProxy
created, where theInvocationHandler
cap (a poem)MethodInterceptor
Responsible for executing the logic of the interceptor chain.Spring AOP provides powerful features to enhance the behavior of the bean, making the cut-side logic separate from the core business logic and improving the modularity and maintainability of the code.