java dynamic proxy - the basic principles Mybaties interceptor chain to achieve

1. Summary

  Mybaties There is a pagination plug-ins, before there deliberately to understand what the principle: https://www.cnblogs.com/jonrain0625/p/11168247.html , pagination plugin from that understanding is based interceptors to achieve Mybaties . this plug-in is a interceptors, and other interceptors interceptor chain Mybaties, and then all the interceptors are made of Executor this dynamic proxy class. The key again to study this dynamic agent, to achieve the effect of a basic interceptor chain. Of course, there are spring aop and many other places are based on dynamic proxy to achieve, on Aop can: https://www.cnblogs.com/lcngu/p/5339555.html  to understand. This is also based on this article, and to learn and implement the code interceptor chain.

2.java dynamic proxy

  java proxy mode and dynamic sub-static agent agent, to achieve dynamic proxy implemented in two ways, one is based on an interface with the JDK to achieve a class-based CGLIB is to achieve, based on the understanding can be seen: HTTPS: / /www.cnblogs.com/rinack/p/7742682.html  .

  2.1 JDK basic use of proxy:

    1. Create a proxy class interfaces

    2. InvocationHandler proxy class that implements the interface execution

    3. Generate proxy object: Proxy.newProxyInstance (loader, interfaces, h);

    4. Use a proxy object

    

 

 

3 illustrates column  

  Column shows a method to achieve the log intercept user class before performing log method, and the interceptor chain LogIntercept1 LogIntercept2 log intercept method of doing business logic, well reflected interceptor chain advantage is that, to achieve coupling, the height can be made to internal changes.

  3.1 New proxy class interfaces and the proxy class

  

public interface Log {
    public void log();
}

 

public class User  implements Log{
    String name = "user1";
    public void log() {
        System.out.println("user1 ----- 登陆");
    }
}

  3.2 New InvocationHandler implementation class

    For packaging, the method called bin Proxy.newProxyInstance create a proxy object, the proxy object and a proxy object injected into the interceptor, the interceptor proxy execution by the invoke method.

  

public class Handler implements InvocationHandler{
    //调用对象
    private Object proxy;
    //目标对象
    private Intercept intercept;
    
    
    private Handler(Intercept target,Object proxy) {
        this.intercept=target;
        this.proxy=proxy;
    }
    public static Object bind(Intercept target,Object proxy){
        return Proxy.newProxyInstance(
                proxy.getClass().getClassLoader()
                , proxy.getClass().getInterfaces(), new Handler(target,proxy));
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        return intercept.intercept(this.proxy,method,args);
    }
}

  3.3 Creating interceptor 

    Implement interceptors and interceptor, lazy writing in a document

  

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public interface Intercept {
    Object intercept(Object o, Method m, Object[]  os );
}
class LogIntercept1 implements Intercept {

    @Override
    public Object intercept(Object o, Method m, Object[] os) {
        try {
            System.out.println("LogIntercept1 拦截登陆操作 做相关业务逻辑");
            return m.invoke(o,os);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
            return  null ; 
        } 
    } 
    
} 
class LogIntercept2 the implements Intercept { 

    @Override 
    public Object Intercept (Object O, Method, m, Object [] OS) {
         the try { 
            System.out.println ( "LogIntercept2 intercept login operation, do the relevant business logic" );
             return m.invoke (O, OS); 
        } the catch (IllegalAccessException | an IllegalArgumentException | a InvocationTargetException E) { 
            e.printStackTrace (); 
            return  null ; 
        } 
    }
}

 

 3.4 Creating a proxy factory 

    In the class based on the number of interceptors, to do the cycle of proxy class. Every proxy regarded interceptor incoming proxy object.

  

package 设计模式.com.pox.logPoxy;

import java.util.ArrayList;
import java.util.List;

public class ProxyFactory {
    
    List<Intercept> InterceptChain = new ArrayList<Intercept>() {
        private static final long serialVersionUID = 1L;

        {
            add(new LogIntercept1());
            add(new LogIntercept2());
        }
    };
    
    
    public  Object  proxy(Class<?> classz) throws Exception {
        try {
            Obj Object = classz.newInstance ();
             return InterceptAll (obj); 
        } the catch (an InstantiationException is | IllegalAccessException E) {
             the throw  new new RuntimeException ( "Exception Agent"); // throw exceptions, no additional anomaly type of design, with RuntimeException place 
        } 
    } 
    
    / ** interceptor agent 
     * @param obj 
     * @return 
     * / 
    Private Object InterceptAll (Object obj) {
         IF (InterceptChain.isEmpty ()) {
             return obj; 
        } 
        for(Intercept Intercept: InterceptChain) { 
            obj = Handler.bind (Intercept, obj); 
        } 
        return obj; 
    } 
    
    // it is to create a single mode of 
    public the ProxyFactory () {
         IF (inner.proxyFactory =! Null ) {
             the throw  new new RuntimeException ( "Create not allow multiple instances" ); 
        } 
    } 
    public  static the ProxyFactory getProxyFactory () {
         return   inner.proxyFactory; 
    } 
    Private  static  class Inner {
         static the ProxyFactory ProxyFactory =new ProxyFactory();
    }
}

 

 

  3.5 Test

public  class the Test {
     public  static  void main (String [] args) throws Exception { 
        the ProxyFactory ProxyFactory = ProxyFactory.getProxyFactory (); 
        the Log User = (the Log) proxyFactory.proxy (the User. class ); 
        USER.LOG (); 
    } 
} 
/ ** 
ouput: 
LogIntercept2 interception landing operation 
LogIntercept1 intercept the landing operation 
user1 ----- landing 
* /

 

 

Above is a simple chain of interceptors to achieve, you can go to access the interceptor chain Mybaties, the principle is the same, if the business need to increase the interceptor chain, implement the interface Intercept, added to the agent factory in ProxyFactory interceptor chain can InterceptChain achieve a high degree of decoupling function.

 

Guess you like

Origin www.cnblogs.com/jonrain0625/p/11431511.html