Cglib (1): Cglib and its basic usage. cglib
Preface
I have been reading the Spring Source Code recently. In fact, I have always known the basic implementation principles of AOP:
- If the Proxy for the interface is used by default, the built-in JDK Proxy + InvocationHandler is used.
- If Cglib is used as proxy for classes
- You can configure the proxy mode to go through Cglib even if the proxy is used for the interface.
Later, I should look at the AOP source code. I am familiar with Proxy + InvocationHandler. I thought that if I studied Cglib, it would be faster to look at the AOP source code, therefore, this article will study what Cglib is, how to use it, and the underlying implementation principles.
What is Cglib?
Cglib is a powerful and high-performanceCode Generation package, Which is widely used by many AOP frameworks for theirMethod Interception. It is the relationship between a Cglib I found on the Internet and some frameworks and languages:
This figure is summarized as follows:
- The bottom layer is Bytecode, which is a virtual instruction format generated by Java to ensure "one compilation and run everywhere", such as iload_0, iconst_1, if_icmpne, dup, etc.
- ASM is located on top of bytecode, which is a framework for directly operating bytecode. The application of ASM needs to be familiar with Java bytecode and Class structure.
- CGLIB, Groovy, and BeanShell are located on ASM. The last two types are not the content in the Java system but the script language. They generate bytecode through the ASM framework to execute Java code in disguise.Running programs in JVM does not have to write Java code-as long as you can generate Java bytecode, JVM does not care about the source of bytecodeOf course, the JVM bytecode generated through Java code is directly generated through the compiler, which is the most "Orthodox" JVM bytecode
- Hibernate and Spring AOP frameworks are located on top of CGLIB, Groovy, and BeanShell, which are familiar to everyone.
- The top layer is Applications, that is, a specific application. Generally, a Web project or a local program is run.
Use Cglib code to proxy classes
The following is an example of Cglib code-proxy for classes. First, define a Dao class with a select () method and an update () method:
public class Dao { public void update() { System.out.println("PeopleDao.update()"); } public void select() { System.out.println("PeopleDao.select()"); }}
Create a Dao proxy to implement the MethodInterceptor interface. The goal is to output two statements before and after the update () method and select () method call:
public class DaoProxy implements MethodInterceptor { @Override public Object intercept(Object object, Method method, Object[] objects, MethodProxy proxy) throws Throwable { System.out.println("Before Method Invoke"); proxy.invokeSuper(object, objects); System.out.println("After Method Invoke"); return object; } }
The Parameter Name of the intercept method is not a native parameter name. I made my own adjustments. The meanings of several parameters are as follows:
- Object indicates the Object to be enhanced
- Method indicates the interception Method.
- Object [] array indicates the parameter list. The basic data type needs to be imported into its packaging type, such as int --> Integer, long-Long, double --> Double
- MethodProxy indicates the proxy for the method, and invokeSuper indicates the call to the method of the proxy object.
Write a test class:
public class CglibTest { @Test public void testCglib() { DaoProxy daoProxy = new DaoProxy(); Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(Dao.class); enhancer.setCallback(daoProxy); Dao dao = (Dao)enhancer.create(); dao.update(); dao.select(); } }
This is a general method of Cglib. setSuperclass indicates the class to be configured as a proxy, and setCallback indicates the implementation class of the Set callback method MethodInterceptor. Use the create () method to generate a proxy object. Note that you should take a look, because the Object is returned. Finally, let's take a look at the running results:
Before Method InvokePeopleDao.update()After Method InvokeBefore Method InvokePeopleDao.select()After Method Invoke
Meets our expectations.
Use Cglib to define different interception policies
A little more extension, for example, we often encounter a complex scenario in AOP:We want to use an interception policy for Method B of Class A, and method C of Class A to use another interception policy..
In this example, we want to use different interception policies for the select () method and the update () method, then we first define a new Proxy:
public class DaoAnotherProxy implements MethodInterceptor { @Override public Object intercept(Object object, Method method, Object[] objects, MethodProxy proxy) throws Throwable { System.out.println("StartTime=[" + System.currentTimeMillis() + "]"); method.invoke(object, objects); System.out.println("EndTime=[" + System.currentTimeMillis() + "]"); return object; } }
The Start Time and end time are output before and after the method call. To meet our needs, implement CallbackFilter:
public class DaoFilter implements CallbackFilter { @Override public int accept(Method method) { if ("select".equals(method.getName())) { return 0; } return 1; } }
The returned value indicates the order. In combination with the following code explanation, the test code needs to be modified:
public class CglibTest { @Test public void testCglib() { DaoProxy daoProxy = new DaoProxy(); DaoAnotherProxy daoAnotherProxy = new DaoAnotherProxy(); Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(Dao.class); enhancer.setCallbacks(new Callback[]{daoProxy, daoAnotherProxy, NoOp.INSTANCE}); enhancer.setCallbackFilter(new DaoFilter()); Dao dao = (Dao)enhancer.create(); dao.update(); dao.select(); } }
The value returned by the CallbackFilter accept method indicates the order. The order is the same as that of the Proxy in setCallbacks. To be clear, there are three Callback in the callback array:
- The Order returned by the method named "select" is 0, that is, using the 0-bit Callback in the callback array, that is, DaoProxy
- If the method name is not "select", the Order returned by the method is 1, that is, the one-bit Callback in the callback array, that is, DaoAnotherProxy.
Therefore, the execution result of the method is:
StartTime=[1491198489261]PeopleDao.update()EndTime=[1491198489275]Before Method InvokePeopleDao.select()After Method Invoke
As expected, because the update () method is not a method named "select", 1 is returned, and 1 is returned using DaoAnotherProxy, that is, the print time; select () the method is the method named "select", so 0 is returned, and 0 is returned using DaoProxy, that is, two sentences are output before and after the method is called.
Here, we need to mention that I specifically defined a NoOp In the Callback array. INSTANCE, which indicates an empty Callback. If you do not want to intercept a method, you can return 2 in DaoFilter. You can try it yourself.
Constructors do not intercept Methods
If the Update () method and select () method are called in the constructor, the two methods are blocked accordingly, what I want now is that the methods called in the constructor will not be blocked. What should I do? First Change the Dao code, add a constructor Dao (), and call the update () method:
public class Dao { public Dao() { update(); } public void update() { System.out.println("PeopleDao.update()"); } public void select() { System.out.println("PeopleDao.select()"); }}
If you do not want to intercept the update () method in the constructor, set setInterceptDuringConstruction (boolean interceptDuringConstruction) to false. The default value is true, that is, the method called in the constructor will also be intercepted. The test method is written as follows:
public class CglibTest { @Test public void testCglib() { DaoProxy daoProxy = new DaoProxy(); DaoAnotherProxy daoAnotherProxy = new DaoAnotherProxy(); Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(Dao.class); enhancer.setCallbacks(new Callback[]{daoProxy, daoAnotherProxy, NoOp.INSTANCE}); enhancer.setCallbackFilter(new DaoFilter()); enhancer.setInterceptDuringConstruction(false); Dao dao = (Dao)enhancer.create(); dao.update(); dao.select(); } }
The running result is:
PeopleDao.update()StartTime=[1491202022297]PeopleDao.update()EndTime=[1491202022311]Before Method InvokePeopleDao.select()After Method Invoke
We can see the call to the first update () method, that is, the call in the Dao class constructor is not intercepted, as expected.
Postscript
This article demonstrates some basic usage of Cglib. Because the principle of Cglib has been explored for a long time, it will not be written in this article, but will be written in the next article.
If you want to use Cglib in depth, you still need to try many Cglib APIs to better use this excellent bytecode generation framework.