Cglib Dynamic Agent

Source: Internet
Author: User

1. What is Cglib

Cglib is a powerful, high-performance, high-quality code generation Class library. It can extend Java classes and implement Java interfaces at run time. But what are the actual functions that ASM provides, and what is ASM? Java bytecode control framework, specifically what you can check the Internet, after all, we are here to discuss is Cglib,cglib is encapsulated ASM, simplifying the operation of ASM, realized in the runtime dynamic generation of new class. You may not feel it's strong, tell you now. In fact, Cglib provides the underlying implementation for spring AOP, and dynamically generates VO/PO (interface-layer objects) for hibernate using Cglib.

Its principle is to use enhancer to generate a subclass of the original class, and set the callback, then the original class of each method call will be transferred to the implementation of the Methodinterceptor interface of the proxy intercept () function:
public Object Intercept (object O,method method,object[] Args,methodproxy proxy)
In the Intercept () function, you can perform an object Result=proxy.invokesuper (O,args), execute the original function, add your own things before and after the execution, change its parameters, or you can cheat and completely do anything else. Plainly, it is the around advice in AOP.

2. How to use Cglib

For example: DAO layer has to increase, delete, change, check operation, if the original DAO layer of the increase, delete, change, check Add permission control, modify the code is very painful. So it can be implemented with AOP. However, the DAO layer does not use interfaces and dynamic proxies are not available. At this time Cglib is a good choice.

Tabledao.java:

Package com.cglib;    public class Tabledao {public      void Create () {          System.out.println ("Create () is running ...");      }      public void Delete () {          System.out.println ("Delete () is running ...");      }      public void Update () {          System.out.println ("Update () is running ...");      public void query () {          System.out.println ("query () is running ...");}  }

  

Implements the Authproxy.java of the Methodinterceptor interface: it is used to intercept the method, increase the access control of the method, and only allow Zhang San access.

Package com.cglib;    Import Java.lang.reflect.Method;    Import Net.sf.cglib.proxy.MethodInterceptor;  Import Net.sf.cglib.proxy.MethodProxy;  Method Interceptor Public  class Authproxy implements Methodinterceptor {      private String userName;      Authproxy (String userName) {          this.username = userName;      }      Used to enhance the original method public      object Intercept (Object arg0, Method Arg1, object[] arg2,              methodproxy arg3) throws Throwable {          //permissions to determine          if (! ") Zhang San ". Equals (UserName)) {              System.out.println (" You don't have permission! ");              return null;          }          Return Arg3.invokesuper (arg0, arg2);      }  

  

Tabledaofactory.java: The factory class used to create subclasses of Tabledao

Package com.cglib;    Import Net.sf.cglib.proxy.Callback;  Import Net.sf.cglib.proxy.Enhancer;  Import net.sf.cglib.proxy.NoOp;    public class Tabledaofactory {      private static Tabledao Tdao = new Tabledao ();        public static Tabledao getinstance () {            return tdao;        }        public static Tabledao getauthinstance (Authproxy authproxy) {            enhancer en = new enhancer ();  Enhancer is used to generate a subclass of an existing class          //Proxy            En.setsuperclass (tabledao.class);           Set the weaving logic          en.setcallback (authproxy);            Generate proxy instance            return (Tabledao) en.create ();        }    

  

Test class Client.java:

Package com.cglib;    public class Client {public        static void Main (string[] args) {    //        Haveauth ();           Havenoauth ();      }        public static void Domethod (Tabledao dao) {            dao.create ();            Dao.query ();            Dao.update ();            Dao.delete ();        }        Impersonation has permission public      static void Haveauth () {            Tabledao Tdao = tabledaofactory.getauthinstance (New Authproxy ("Zhang San")) ;            Domethod (Tdao);        }        Impersonation without permissions public      static void Havenoauth () {            Tabledao Tdao = tabledaofactory.getauthinstance (New Authproxy ("John Doe" ));            Domethod (Tdao);        }  

  

This allows you to control the way the DAO layer is privileged. But if you change the demand, to the DAO layer of the Query method for all users can access, and other methods still have permission control, how to implement it? This is hard for us, because we used cglib. The simplest way of course is to modify our method interceptors, but this complicates the logic and is not conducive to maintenance. Fortunately Cglib provides us with a method filter (Callbackfilter), Callbackfilte can clearly show that the different methods in the class being proxied are intercepted by which interceptor. Let's make a filter to filter the Query method.

Authproxyfilter.java:

Package com.cglib;    Import Java.lang.reflect.Method;    Import Net.sf.cglib.proxy.CallbackFilter;  Import net.sf.cglib.proxy.NoOp;    public class Authproxyfilter implements Callbackfilter {public        int accept (Method arg0) {          /           * * If the call is not a query method, call the Authproxy interceptor to determine the permissions           *          /if (!) Query ". Equalsignorecase (Arg0.getname ())) {              return 0;//Call the first method interceptor, that is, Authproxy          }/           * * To invoke the second method interceptor, That is, Noop.instance,noop.instance is an interceptor that doesn't do anything.           * Here is anyone with access to the Query method, so call the default interceptor without doing any processing */          return 1;        }    

  

As for why return 0 or 1, the comment is very detailed.

Add the following method to the Tabledaofactory.java:

public static Tabledao Getauthinstancebyfilter (Authproxy authproxy) {          enhancer en = new enhancer ();          En.setsuperclass (tabledao.class);           En.setcallbacks (New callback[]{authproxy,noop.instance});  Set two method Interceptor         En.setcallbackfilter (New Authproxyfilter ());          Return (Tabledao) en.create ();       }    

  

Note here that the array parameter order in the En.setcallbacks () method is the method interceptor represented by the return value of the method above, and if return 0 uses the Authproxy interceptor, return 1 uses the Noop.instance Interceptor, Noop.instance is the default method interceptor and does not do any processing.

The following methods are added to the test class:

Impersonation permission filter public     static void Haveauthbyfilter () {           Tabledao Tdao = Tabledaofactory.getauthinstancebyfilter (new Authproxy ("Zhang San"));           Domethod (Tdao);           Tdao = Tabledaofactory.getauthinstancebyfilter (New Authproxy ("John Doe"));           Domethod (Tdao);       }   

  

The method is called in the Main method, and the result of the program runs as follows:

Create () is running ...
Query () is running ...
Update () is running ...
Delete () is running ...
You have no authority!
Query () is running ...
You have no authority!
You have no authority!

In this case, all users have access to the query method, while other methods allow only Zhang San access.

Cglib Dynamic Agent

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.