SoFunction
Updated on 2025-03-09

Detailed explanation of the implementation principle of Spring AOP and examples

Detailed explanation of the implementation principle of Spring AOP and examples

Spring implements AOP based on JDK dynamic proxy and CGLIB proxy implementation.

The following is a brief introduction to JDK dynamic proxy and CGLIB proxy

JDK dynamic proxy: Its proxy object must be an implementation of a certain interface, which completes the proxy of the target object by creating an interface implementation class during operation.

CGLIB proxy: The implementation principle is similar to JDK dynamic proxy, except that the proxy object it generates during runtime is a subclass extended to the target class. CGLIB is an efficient code generation package. The underlying layer is achieved by operating bytecode by ASM (open source Java bytecode editorial library), and its performance is stronger than JDK.

In Spring, when there is an interface, the proxy proxy object will be implemented in JDK. When there is no interface, the proxy object in cglib will be implemented. Details are as follows:

// JDK method: PersonService is an interface, PersonServiceBean is an implementation class, 
 public class JDKProxyFactory implements InvocationHandler { 
  private Object targetObject; 
   
  public Object createProxyIntance(Object targetObject) 
  { 
  =targetObject; 
  return (().getClassLoader(),  
   ().getInterfaces(), this); 
  } 
 
public Object invoke(Object proxy, Method method, Object[] args) 
 throws Throwable { 
  PersonServiceBean person=(PersonServiceBean); 
  Object result=null; 
   if(()!=null) 
   {  
   result = (targetObject, args); 
   } 
  return result; 
} 
} 
//Use the CGlib package to implement: PersonServiceBean is an implementation class, but does not have a PersonService interface. 
public class CGlibProxyFactory implements MethodInterceptor{ 
 private Object targetObject; 
  
 public Object createProxyInstance(Object targetObject) 
 {  
  =targetObject; 
  Enhancer enhancer=new Enhancer(); 
  (());//Set the subclass of the target class, which will override non-final methods in all parent classes  (this);//Set callback return (); 
 } 
 
public Object intercept(Object proxy, Method method, Object[] args, 
 MethodProxy methodProxy) throws Throwable { 
 PersonServiceBean person=(PersonServiceBean); 
  Object result=null; 
   if(()!=null) 
   {  
   result = (targetObject, args); 
   } 
 return null; 
} 
} 

Thank you for reading, I hope it can help you. Thank you for your support for this site!