Home  >  Article  >  Java  >  Detailed explanation of static, dynamic proxy and CGLIB dynamic proxy in Java (picture)

Detailed explanation of static, dynamic proxy and CGLIB dynamic proxy in Java (picture)

黄舟
黄舟Original
2017-08-08 10:02:171478browse

This article mainly introduces the static proxy, dynamic proxy and CGLIB dynamic proxy summary in JAVA. It has certain reference value. If you are interested, you can learn about it

The proxy mode is the most commonly used design in Java One of the patterns, especially widely used in the spring framework. For Java's proxy mode, it can generally be divided into: static proxy, dynamic proxy, and CGLIB dynamic proxy.

The above three proxy modes will be explained separately.

1. Static proxy

Static proxy actually means writing the proxy class of the proxy method in advance before the program is run, and then running it after compilation. The class already exists before the program is run.
Below we implement a static proxy demo:

Static proxy

Define an interface Target


package com.test.proxy;

public interface Target {

  public String execute();
}

TargetImpl implements the interface Target


package com.test.proxy;

public class TargetImpl implements Target {

  @Override
  public String execute() {
    System.out.println("TargetImpl execute!");
    return "execute";
  }
}

Agent class


package com.test.proxy;

public class Proxy implements Target{

  private Target target;

  public Proxy(Target target) {
    this.target = target;
  }

  @Override
  public String execute() {
    System.out.println("perProcess");
    String result = this.target.execute();
    System.out.println("postProcess");
    return result;
  }
}

Test class:


package com.test.proxy;

public class ProxyTest {

  public static void main(String[] args) {

    Target target = new TargetImpl();
    Proxy p = new Proxy(target);
    String result = p.execute();
    System.out.println(result);
  }

}

Running result:


perProcess
TargetImpl execute!
postProcess
execute

Static proxy needs to write the proxy class in advance for the proxy method. If it is proxy There are many methods and a lot of code needs to be written. Therefore, the above shortcomings are made up for by dynamic proxy.

2. Dynamic proxy

Dynamic proxy mainly uses the reflection mechanism to dynamically generate the required proxy class at runtime.

Dynamic proxy

Interface


package com.test.dynamic;

public interface Target {

  public String execute();
}

Implementation class


##

package com.test.dynamic;

public class TargetImpl implements Target {

  @Override
  public String execute() {
    System.out.println("TargetImpl execute!");
    return "execute";
  }
}

Agent Class


package com.test.dynamic;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class DynamicProxyHandler implements InvocationHandler{

  private Target target;

  public DynamicProxyHandler(Target target) {
    this.target = target;
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    System.out.println("========before==========");
    Object result = method.invoke(target,args);
    System.out.println("========after===========");
    return result;
  }
}

Test class


package com.test.dynamic;

import java.lang.reflect.Proxy;

public class DynamicProxyTest {

  public static void main(String[] args) {
    Target target = new TargetImpl();
    DynamicProxyHandler handler = new DynamicProxyHandler(target);
    Target proxySubject = (Target) Proxy.newProxyInstance(TargetImpl.class.getClassLoader(),TargetImpl.class.getInterfaces(),handler);
    String result = proxySubject.execute();
    System.out.println(result);
  }

}

Run result:


========before==========
TargetImpl execute!
========after===========
execute

Whether it is a dynamic proxy or a static leader, an interface needs to be defined before the proxy function can be implemented. This also has limitations, so in order to solve this problem, a third proxy method emerged: cglib proxy.

3.cglib agent

CGLib uses very low-level bytecode technology. The principle is to create a subclass for a class through bytecode technology, and then The method interception technology is used in subclasses to intercept all calls to parent class methods and weave in cross-cutting logic accordingly. Both JDK dynamic proxy and CGLib dynamic proxy are the basis for implementing Spring AOP.

cglib dynamic proxy


Target class


package com.test.cglib;

public class Target {

  public String execute() {
    String message = "-----------test------------";
    System.out.println(message);
    return message;
  }
}

General proxy class:


package com.test.cglib;

import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class MyMethodInterceptor implements MethodInterceptor{

  @Override
  public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
    System.out.println(">>>>MethodInterceptor start...");
    Object result = proxy.invokeSuper(obj,args);
    System.out.println(">>>>MethodInterceptor ending...");
    return "result";
  }
}

Test class


package com.test.cglib;

import net.sf.cglib.proxy.Enhancer;

public class CglibTest {

  public static void main(String ... args) {
    System.out.println("***************");
    Target target = new Target();
    CglibTest test = new CglibTest();
    Target proxyTarget = (Target) test.createProxy(Target.class);
    String res = proxyTarget.execute();
    System.out.println(res);
  }

  public Object createProxy(Class targetClass) {
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(targetClass);
    enhancer.setCallback(new MyMethodInterceptor());
    return enhancer.create();
  }

}

Execution result:


***************
>>>>MethodInterceptor start...
-----------test------------
>>>>MethodInterceptor ending...
result

The generation process of the proxy object is implemented by the Enhancer class. The approximate steps are as follows:


1. Generate the binary bytecode of the proxy class Class;


2. Through Class .forName loads the binary bytecode and generates the Class object;


3. Obtain the instance structure through the reflection mechanism and initialize the proxy class object.


The above is the detailed content of Detailed explanation of static, dynamic proxy and CGLIB dynamic proxy in Java (picture). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn