[Reserved] interview spring aop test sites

Q: Spring's AOP is how to achieve?

Solution: Spring AOP dynamic proxy There are two main ways, JDK dynamic proxies and CGLIB dynamic proxy.

JDK dynamic proxy proxy class to receive by reflection, and requires the proxy class must implement an interface.

The core JDK dynamic proxy is InvocationHandler interface and the Proxy class.

If the target class does not implement the interface, then Spring AOP will choose to use dynamic proxy CGLIB target class.

CGLIB (Code Generation Library), is a code generation library may be a subclass of a class dynamically generated at runtime, note, through inheritance CGLIB-way to do dynamic proxy, so if a class is marked as final, then it can not be used for dynamic CGLIB agent.

 

Q: CGLIB Dynamic Function: without changing the Test class, print a word before the method target, after printing a word.

public class UserServiceImpl implements UserService {
    @Override
    public void add() {
        // TODO Auto-generated method stub
        System.out.println("--------------------add----------------------");
    }
}
Solution: 

public  class CglibProxy the implements MethodInterceptor {  
  Private Enhancer Enhancer = new new Enhancer ();  
  public Object The getProxy (Class clazz) {  
    // Set create classes subclass   
    enhancer.setSuperclass (clazz);   
    enhancer.setCallback ( the this );  
    // dynamically creating a subclass instance bytecode technique   
    eturn enhancer.create ();   
   }   
   // implement interface method MethodInterceptor   
  public Object Intercept (Object obj, method, method, Object [] args, MethodProxy Proxy) throws the Throwable {   
    System.out.println ( "pre-agent");  
    // method call by the proxy class parent class   
    Object Result = proxy.invokeSuper (obj, args);   
    System.out.println ( "rear Agent" );  
     return Result;   
  }   
}   

public  class DoCGLib {  
   public  static  void main (String [] args) {   
      CglibProxy proxy = new new CglibProxy ();  
      // create a proxy class by subclassing manner   
      UserServiceImpl proxyImp = (UserServiceImpl) proxy.getProxy (UserServiceImpl. class );   
      proxyImp.add ();   
    }   
}

 

Guess you like

Origin www.cnblogs.com/smallwangmusk/p/11479906.html