Cglib Dynamic Agent Combat

Source: Internet
Author: User
Tags aop reflection
What's cglib?

Cglib is a powerful, high-performance, high-quality code generation Class library. It can extend Java classes and implement Java interfaces at runtime.
Official Introduction:

The Cglib-byte code Generation Library is the high level API to generate and transform Java Byte code. It is used through AOP, testing, data access frameworks to generate dynamic proxy objects and intercept field access. Https://github.com/cglib/cglib/wiki

Of course these actual functions are provided by ASM, ASM is a Java bytecode control framework, official introduction:

ASM is a all purpose Java bytecode manipulation and analysis
Framework. It can be used to modify existing classes or dynamically
Generate classes, directly in binary form. Provided common
Transformations and analysis algorithms allow to easily assemble
Custom Complex transformations and code analysis tools.

Specific can go to ASM website detailed understanding: http://asm.ow2.org/.
Cglib encapsulates ASM, simplifies ASM operations, and enables dynamic generation of new classes at runtime.
The Spring AOP low-level implementation is cglib;hibernate using Cglib to dynamically generate VO/PO (interface layer objects). dynamic Agents in the JDK

The dynamic proxies in the JDK are implemented by reflection class proxies and Invocationhandler callback interfaces, and students who don't understand this can refer to this blog on Infoq: Java depth Adventure (vii)--java reflection and dynamic Proxy
But the dynamic proxy in JDK has a disadvantage: the class that is being dynamically represented must implement an interface, that is, it can only proxy the methods defined in the interface implemented by the class, which has some limitations in practical programming and is not very efficient in using reflection. Second, Cglib combat

Using Cglib to implement dynamic proxies is completely unaffected by the need for proxy classes to implement interfaces, and the Cglib base uses the ASM bytecode generation framework to generate proxy classes using bytecode technology, which is much more efficient than using Java reflection. The only thing to note is that Cglib cannot broker a class that is declared final because the Cglib principle is to dynamically generate subclasses of the proxy class.
2.1 using Methodinterceptor to implement AOP
1) First, the proxy class Userdao

Package com.ricky.cglib;

/**
 * Required Class
 * @author Ricky Fung
 * */public
class Userdao {public

    long Insert () {
        System . Out.println ("Insert () is executing!");
        return 1;
    }

    public void query () {
        System.out.println (' query () is executing! ');
    }

    public int update () {
        System.out.println ("Update () is executing!");
        return 1;
    }

    public int Delete () {
        System.out.println (' delete () is executing! ');
        return 1;
    }

}

Here the proxy class is a normal Java class, without implementing any interfaces.

2) Method Interceptor

Package com.ricky.cglib.interceptor;

Import Java.lang.reflect.Method;
Import Net.sf.cglib.proxy.MethodInterceptor;
Import Net.sf.cglib.proxy.MethodProxy;

public class Aopinterceptor implements Methodinterceptor {public  

    object intercept (Object arg0, Method Arg1, object[] Arg2,  
            methodproxy arg3) throws Throwable {System.out.println  

        ("before method Execute");

        Object obj = Arg3.invokesuper (arg0, arg2);

        System.out.println ("After method Execute");

        return obj;  
    }  
}  

In the interceptor, we can intercept the proxy class method, which I have handled before and after the execution of the method to simulate AOP.
3 Finally the client code

Package com.ricky.cglib.interceptor;

Import Com.ricky.cglib.UserDao;
Import Net.sf.cglib.proxy.Enhancer;
Import Net.sf.cglib.proxy.MethodInterceptor;

/**
 * Implements AOP
 * @author Ricky Fung
 */public
class Methodinterceptordemo {public

    static void Main (string[] args) {

        new Methodinterceptordemo (). run ();

    private void Run () {

        Userdao Userdao = getproxyinstance (New Aopinterceptor ());
        Userdao.insert ();
        Userdao.query ();
    }

    Public Userdao getproxyinstance (Methodinterceptor methodinterceptor) {  
        enhancer en = new enhancer ();
        Conduct Agent 
        en.setsuperclass (userdao.class);  
        En.setcallback (methodinterceptor);  
        Generate proxy instance return  
        (Userdao) en.create ();  
    }  

The proxy class is generated through the Create method of the enhancer class provided by Cglib.
Run it and see the results:

Before method Execute
Insert () is executing!
After method execute
Before method Execute
Query () is executing!
After method execute

With the method interceptor provided by Cglib, we can easily implement AOP programming.

2.2 Method Filter (Callbackfilter)
In the example above, we intercepted the Userdao crud method, and what if we only wanted to intercept methods other than query. Of course the easiest way to do this is to modify our method interceptor, but it complicates the logic and is not conducive to maintenance. Fortunately Cglib has provided us with a method filter (Callbackfilter), callbackfilter can clearly indicate that the different methods in the proxy class are intercepted by which interceptor.
The API documentation is as follows:

Here we will implement a filter to filter the Query method.

Package com.ricky.cglib.filter;

Import Java.lang.reflect.Method;
Import Net.sf.cglib.proxy.CallbackFilter;

public class Mycallbackfilter implements callbackfilter{public

    int Accept (method arg0) {
        if (!) Query ". Equalsignorecase (Arg0.getname ()) return  
            0;
        return 1;
    }
}

Callbackfilter interface has only one accept method

method returns the meaning of a value

The index into the "array of" callbacks (as specified by Enhancer.setcallbacks (net.sf.cglib.proxy.callback[)) to a for th E method,

The return value is the index position in the callback array, which means the current method specifies which interceptor to proceed.

The client code is as follows

package com.ricky.cglib.filter;
Import Net.sf.cglib.proxy.Callback;
Import Net.sf.cglib.proxy.Enhancer;
Import Net.sf.cglib.proxy.MethodInterceptor;
Import net.sf.cglib.proxy.NoOp;
Import Com.ricky.cglib.UserDao;

Import Com.ricky.cglib.interceptor.AopInterceptor;

        /** * Method Filter * @author Ricky Fung * * */public class Callbackfilterdemo {public static void main (string[] args) {
    New Callbackfilterdemo (). run ();
        private void Run () {Userdao Userdao = getproxyinstance (New Aopinterceptor ());
        Userdao.insert ();
    Userdao.query ();
        Public Userdao getproxyinstance (methodinterceptor methodinterceptor) {enhancer en = new enhancer ();  
        Conduct Agent En.setsuperclass (Userdao.class);  
        En.setcallbacks (New Callback[]{methodinterceptor, noop.instance});  
        En.setcallbackfilter (New Mycallbackfilter ());  
    Generate proxy instance return (Userdao) en.create (); }  

}

Where Noop.instance is an interceptor that is provided by Cglib without any action. When we return 1 in the Mycallbackfilter accept method, we actually specify it to intercept the query method.

Run it and see the results.

Before method Execute
Insert () is executing!
After method execute
Query () is executing!

The Insert method was found to be blocked, and the query method was not intercepted.

Finally, attach the sample code: Https://github.com/FBing/cglib-demo

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.