Static proxy and dynamic proxy

Posted Jun 16, 20202 min read

Background

Both static and dynamic proxies are created to facilitate AOP programming(aspect-oriented programming). AOP programming is a lateral enhancement of proxy objects, which isolates core business agents from peripheral business code.

Static proxy

Static proxy means that the AOP framework generates AOP proxy classes during the compilation phase, so it is also called compilation-time enhancement.

  1. Hard-coded implementation, abstracting the object to be enhanced, and performing enhancement processing before and after the method to be enhanced
  2. ApsectJ is one of the implementations of static proxy and is also the most popular. Static agents generate proxy classes at compile time, which is more efficient than dynamic proxies. AspectJ can be used alone or in combination with Spring.

Dynamic proxy

Unlike a static proxy, a dynamic proxy means that the AOP framework does not modify the bytecode generated at compile time, but generates an AOP proxy object in memory at runtime. This AOP object contains all the methods of the target object, and Specific pointcuts have been enhanced, and call back the original object method.
There are two main ways of dynamic proxy in Spring AOP:JDK dynamic proxy and CGLIB dynamic proxy.

  1. JDK dynamic proxy:Process the proxyed class through reflection, and require that the proxyed class must implement an interface. The core class is the InvocationHandler interface and the Proxy class. When the target class does not implement the interface, the Spring AOP framework will use CGLIB to dynamically proxy the target class(see DefaultAopProxyFactory::createAopProxy, CglibAopProxy::getProxy). CGLIB(Code Generation Library) is a class library for code generation, which can dynamically generate subclasses of a class at runtime.
  2. CGLIB dynamic proxy:It is a powerful and high-performance code generation package, which is a dynamic proxy that is done through inheritance. Therefore, if a class is marked as final, it cannot use CGLIB as a dynamic proxy. of. The core class is the MethodInterceptor interface and the Enhancer class. The bottom layer uses a small and fast bytecode processing framework ASM to convert the bytecode and generate a new class

CGLIB application

AOP, HIbernate proxy single-ended(many to one, one to one), EasyMock and JMock are packages that use mock objects to test Java code

Leading knowledge:reflection
Next article:How is AOP applied in Spring?