preface

In spring, it was mentioned that the principle of AOP is to use dynamic proxy. This article will write about JDK proxy and Cglib proxy.

First post the relevant objects and interfaces that need to be propped up.

The first is the interface:

public interface TestDao {
  void test();
}
Copy the code

Then there is the implementation class:

public class TestDaoImpl implements TestDao { @Override public void test() { System.out.println("test dao impl"); }}Copy the code

1.JdkProxy

JDK dynamic proxies: JDK dynamic proxies can only generate proxies for classes that implement interfaces;

Jdk dynamic proxies make use of reflection by calling InvokeHandle before or after invoking a specific method.

To implement a concrete Jdk dynamic proxy, start by writing a class that implements InvokeHandle and implements its invoke() method

The JdkProxy constructor takes a generic Object as an argument, and then we can use reflection to create a Jdk dynamic proxy factory class:

Next, write a test class to test the above code:

public static void main(String[] args) {
    TestDao jdkDao = JdkDynamicObjectFactory.getProxiedObject(TestDaoImpl.class);
    jdkDao.test();
  }
Copy the code

Run the test code and you can see the console output:

jdk dynamic before...
test dao impl
jdk dynamic after...
Copy the code

This completes the Jdk dynamic proxy and enhances the target object.

2.CglibProxy

Cglib dynamic proxy: Cglib implements a proxy for a class, mainly by generating a subclass of a specified class that overrides its methods.

CglibProxy = CglibProxy = CglibProxy

Then write a proxy factory Class as well, taking a Class:

Also, write a test class to test the cglib dynamic proxy:

public static void main(String[] args) {
    TestDao cglibDao = CglibObjectFactory.getProxiedObject(TestDaoImpl.class);
    cglibDao.test();
  }
Copy the code

Run the test code and the console output looks like this:

cglib before...
test dao impl
cglib after...
Copy the code

This enables cglib dynamic proxies and enhances the target object.

3. Summary

A. JDK proxy can only be used for classes that implement interfaces, while cglib proxy can be used for common classes.

B. JDK proxy implements dynamic proxy through reflection, while Cglib implements dynamic proxy by generating a subclass for the target class.

C. Because the cglib proxy generates a subclass for the target class and enhances the parent method, the target class cannot be modified with final;