The Implementation Principle of Spring AOP and Its Example

Posted by StefanRSA on Mon, 14 Oct 2019 17:25:54 +0200

The Implementation Principle of Spring AOP and Its Example
spring implements AOP by relying on JDK dynamic proxy and CGLIB proxy.
Following is a brief introduction to JDK dynamic proxy and CGLIB proxy
JDK dynamic proxy: Its proxy object must be the implementation of an interface. It is the proxy of the target object by creating an implementation class of the interface during operation.
CGLIB proxy: The implementation principle is similar to that of JDK dynamic proxy, except that the proxy object generated during operation is a subclass extended for the target class. CGLIB is an efficient code generation package. The bottom layer is realized by ASM (open source Java bytecode editing class library) which operates bytecode. The performance of CGLIB is better than JDK.
In Spring, the proxy proxy proxy object will be implemented by JDK when there is an interface, and in cglib when there is no interface, the proxy proxy object will be implemented by the way of cglib. Details are as follows:

// JDK: PersonService is the interface and PersonService Bean is the implementation 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; 
} 
} 
//Using the CGlib package: PersonServiceBean implements the class without the 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());//Set a subclass of the target class that overrides non-final methods in all parent classes 
  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 you, thank you for your support!

Topics: JDK Spring Java