• JDK dynamic proxies are interfaces that implement proxied objects, and Cglib is interfaces that inherit proxied objects.
  • Both JDK and Cglib generate bytecodes at runtime. JDK writes Class bytecodes directly, while Cglib uses the ASM framework to write Class bytecodes. The Cglib proxy implementation is more complex, and the generation of proxy classes is less efficient than JDK.
  • JDK calls proxy methods through reflection. Cglib calls methods directly through FastClass. Cglib is more efficient.
  • Methods in the same class nested calls, on the inner layer of the method to enhance the difference in effect

Cglib dynamic proxy, proxy.invokesuper (proxy, args) is used to invoke test2() from test1() in the same class. If test1() and test2() are both proxied, test1() and test2() will be enhanced. Methodproxy.invoke (Target, args), will only be enhanced to test1(). The difference is whether the execution object passed in is a proxy object or a proxied object.

The JDK dynamic proxy calls test2() on the same class as test1(). If both methods are propped, only test1() will be enhanced, not test2()

Explanation:

  1. The JDK dynamic proxy approach to rewrite the Java. Lang. Reflect the InvocationHandler# invoke method
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("> > > > > > > > > > > > > > > > > > > > > >");
        Object result = method.invoke(target, args);
        return result;
    }
Copy the code

Incorrect usage

  • Method.invoke (proxy, args), an infinite loop

Proper use

  • Pass in the target class object target and use method.invoke(target, args) to execute the target method of the propped class
  1. Additional dynamic proxy way to rewrite the org. Springframework. Additional, proxy. MethodInterceptor# intercept method
    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("Here is an enhancement to the target class!!"+ method.getName()); // Notice that the method call is not reflection. Object object = proxy.invokeSuper(proxy, args);return object;
    }
Copy the code

Incorrect usage

  • proxy.invoke(proxy, args); There is an infinite loop that calls methods in the proxy and executes the enhanced word method #test1() in the proxy class

Proper use

  • Use the proxy. InvokeSuper (proxy, args); #CGLIB$test1$2()
  • Pass target, methodProxy.invoke(target, args); This approach is used by the Spring CglibAopProxy class