Detailed Explanation and Example of Implementation Principle of Spring AOP

  • 2021-12-13 08:59:38
  • OfStack

Detailed Explanation and Example of Implementation Principle of Spring AOP

The spring implementation of AOP relies on the JDK dynamic proxy and the CGLIB proxy implementation.

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

JDK Dynamic Proxy: Its proxy object must be an implementation of an interface, which is to complete the proxy for the target object by creating an implementation class of an interface during runtime.

CGLIB proxy: The implementation principle is similar to JDK dynamic proxy, except that the proxy object it generates at run time is a subclass for the target class extension. CGLIB is an efficient code generation package. The bottom layer is implemented by ASM (open source Java ByteCode editing class library), and its performance is better than JDK.

In Spring, proxy proxy object will be implemented by JDK when there is an interface, and prixy proxy object will be implemented by cglib when there is no interface. Details are as follows:


// JDK Mode: PersonService Is the interface, PersonServiceBean To implement the class,  
 
 public class JDKProxyFactory implements InvocationHandler { 
  private Object targetObject; 
   
  public Object createProxyIntance(Object targetObject) 
  { 
  this.targetObject=targetObject; 
  return Proxy.newProxyInstance(this.targetObject.getClass().getClassLoader(),  
   this.targetObject.getClass().getInterfaces(), this); 
  } 
 
public Object invoke(Object proxy, Method method, Object[] args) 
 throws Throwable { 
  PersonServiceBean person=(PersonServiceBean)this.targetObject; 
  Object result=null; 
   if(person.getUser()!=null) 
   {  
   result = method.invoke(targetObject, args); 
   } 
  return result; 
} 
} 

// Use CGlib Package implementation: PersonServiceBean To implement the class,    And there is no PersonService Interface,       
 
public class CGlibProxyFactory implements MethodInterceptor{ 
 private Object targetObject; 
  
 public Object createProxyInstance(Object targetObject) 
 {  
  this.targetObject=targetObject; 
  Enhancer enhancer=new Enhancer(); 
  enhancer.setSuperclass(this.targetObject.getClass());// Sets a subclass of the target class that overrides all non- final Method  
  enhancer.setCallback(this);// Set callback  
 return enhancer.create(); 
 } 
 
public Object intercept(Object proxy, Method method, Object[] args, 
 MethodProxy methodProxy) throws Throwable { 
 PersonServiceBean person=(PersonServiceBean)this.targetObject; 
  Object result=null; 
   if(person.getUser()!=null) 
   {  
   result = methodProxy.invoke(targetObject, args); 
   } 
 return null; 
} 
} 

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: