Cglib Simple Introduction __java

Source: Internet
Author: User
Tags aop auth
Cglib Overview:
Cglib (Code Generation Library) is a powerful, high-performance, high-quality Code Generation class library. It can extend Java classes and implement Java interfaces at runtime.
The Cglib encapsulates the ASM, which can dynamically generate new classes at run time.
Cglib used in AOP,JDK must be based on interfaces, Cglib without this restriction.

Cglib Application:
With an example, the application of Cglib is briefly introduced.
We simulate a virtual scene, about the management of information.

1 The original requirement is anyone can manipulate the information of the create,update,delete,query operation.
Infomanager.java--encapsulating the operation of the information
public class Infomanager {
Simulate query operations
public void query () {
SYSTEM.OUT.PRINTLN ("Query");
}
Impersonation Creation Action
public void Create () {
System.out.println ("create");
}
Simulate Update operation
public void Update () {
SYSTEM.OUT.PRINTLN ("Update");
}
Simulate a delete operation
public void Delete () {
System.out.println ("delete");
}
} Infomanagerfactory.java--factory class
public class Infomanagerfactory {
private static Infomanager manger = new Infomanager ();
/**
* Create the original Infomanager
*
* @return
*/
public static Infomanager getinstance () {
return manger;
}
} Client.java--For client calls
public class Client {

public static void Main (string[] args) {
Client C = new Client ();
C.anyonecanmanager ();
}

/**
* Simulation: No permission required, anyone can operate
*/
public void Anyonecanmanager () {
SYSTEM.OUT.PRINTLN ("Any one can do manager");
Infomanager manager = Infomanagerfactory.getinstance ();
Docrud (manager);
Separatorline ();
}

/**
* Add/Update/delete/query operations on info
*
* @param Manager
*/
private void Docrud (Infomanager manager) {
Manager.create ();
Manager.update ();
Manager.delete ();
Manager.query ();
}

/**
* Add a separate line to differentiate
*/
private void Separatorline () {
System.out.println ("################################");
}

At this point, there is no cglib content, because the requirements are too simple, but then the requirements changed, asking:

2 only a user named "Maurice" is logged in to allow the create,update,delete,query operation of the information.
What to do. Do you want to add a permission decision before each method? This repeated logic too much, and then thought of proxy (proxy mode), but the original Infomanager also did not implement interface, can not use the JDK proxy. So cglib here is going to be a grand debut.
Once you use Cgblig, you need only add a Methodinterceptor class and modify the factory code to achieve this requirement.
Authproxy.java--Permission validation proxy class
public class Authproxy implements Methodinterceptor {

private String name; Member Login Name

Public Authproxy (String name) {
this. Name = name;
}

/**
* Permission check, if member name is: Maurice, then have permission to do operation, otherwise prompt does not have permission
*/
@Override
Public Object intercept (object obj, Method method, object[] args, Methodproxy proxy) throws Throwable {
if (! "Maurice". Equals (this. Name)) {
System.out.println ("Authproxy:you have no permits to do manager!");
return null;
}
return Proxy.invokesuper (obj, args);
}

Public String GetName () {
return name;
}

public void SetName (String name) {
this. Name = name;
}

} Infomanagerfactory.java--code changes are as follows:
public class Infomanagerfactory {

/**
* Create a Infomanager with permission test
*
* @param auth
* @return
*/
public static Infomanager getauthinstance (Authproxy auth) {
Enhancer enhancer = new enhancer ();
Enhancer.setsuperclass (Infomanager. Class);
Enhancer.setcallback (auth);
Return (Infomanager) enhancer.create ();
}


}
Client.java--code changes as follows
public class Client {

public static void Main (string[] args) {
Client C = new Client ();
C.havenoauthmanager ();
C.haveauthmanager ();
}

/**
* Simulation: Login member does not have permission
*/
public void Havenoauthmanager () {
System.out.println ("The Loginer ' name is isn't maurice,so have no permits do manager");
Infomanager Noauthmanager = infomanagerfactory.getauthinstance (New Authproxy ("Maurice1"));
Docrud (Noauthmanager);
Separatorline ();
}

/**
* Simulation: Login Member has permission
*/
public void Haveauthmanager () {
System.out.println ("The Loginer ' s name is Maurice,so have permits does manager");
Infomanager AuthManager = infomanagerfactory.getauthinstance (New Authproxy ("Maurice"));
Docrud (AuthManager);
Separatorline ();
}

/**
* Add/Update/delete/query operations on info
*
* @param Manager
*/
private void Docrud (Infomanager manager) {
Manager.create ();
Manager.update ();
Manager.delete ();
Manager.query ();
}

/**
* Add a separate line to differentiate
*/
private void Separatorline () {
System.out.println ("################################");
}

Execute the following code and find that the client side has the right checksum already added.
Also is Infomanager, why at this time can have more authority judgment. What exactly is the object that Enhancer.create () returns in factory. This question will be explained in the third part of the cglib.
This side of the code, in fact, introduced the cglib in the enhancer function.

Here, referring to the above code, you can use the AOP features brought by Cglib. But for more information on the functionality of the Cglib, the simulation needs have changed again:

3 because the query function users Maurice can be used to attract other users of the strong complaints, so the right to change again, only create,update,delete, only need rights protection, query anyone can use.
What to do. The use of authproxy, so that all the methods in Infomanager are agents, plus the judgement of the Authority. Of course, the easiest way to think about it is to do it in the Authproxy intercept method, and if the agent is query, it does not require permission validation. This can be done, but once the logic is more complex, intercept this method will do a lot of things, logic will be unusually complex.
Fortunately, Cglib also provided the Callbackfilter. Using Callbackfilter, it is clear that different methods in the proxy class (Infomanager) are intercepted by which interceptor (Interceptor).
Authproxyfilter.java
public class Authproxyfilter implements Callbackfilter {

private static final int auth_need = 0;
private static final int auth_not_need = 1;

/**
* <pre>
* Select Proxy to use
* If the query function is invoked, the second proxy is used
* Otherwise, use the first proxy
* </pre>
*/
@Override
public int Accept (method method) {
if ("Query". Equals (Method.getname ()) {
return auth_not_need;
}
return auth_need;
}

What does this piece of code mean. The Accept method means that if the proxy method is query (), the second interceptor is used to intercept, and if the proxy method is not query (), then the first interceptor is used to intercept. So we just have to write an interceptor, do not do the right check on the line. (In fact, the cglib in the noop.instance is an empty interceptor, as long as the configuration on this can be.) )
Infomanagerfactory.java--The code is modified as follows: (Configure different interceptors and filter)
public class Infomanagerfactory {

/**
* Create Infomanager with different permission requirements
*
* @param auth
* @return
*/
public static Infomanager getselectivityauthinstance (Authproxy auth) {
Enhancer enhancer = new enhancer ();
Enhancer.setsuperclass (Infomanager. Class);
Enhancer.setcallbacks (new callback[] {auth, noop.instance});
Enhancer.setcallbackfilter (New Authproxyfilter ());
Return (Infomanager) enhancer.create ();
}

Remember: The Order of the Interceptor (Interceptor) in the setcallbacks must be the same as the order specified in Callbackfilter. Avoid.

Client.java
public class Client {

public static void Main (string[] args) {
Client C = new Client ();
C.selectivityauthmanager ();
}

/**
* Simulation: Member without permission, can do query operation
*/
public void Selectivityauthmanager () {
System.out.println ("The Loginer ' s name is not maurice,so have no permits does manager except do query operator");
Infomanager AuthManager = infomanagerfactory.getselectivityauthinstance (New Authproxy ("Maurice1"));
Docrud (AuthManager);
Separatorline ();
}

/**
* Add/Update/delete/query operations on info
*
* @param Manager
*/
private void Docrud (Infomanager manager) {
Manager.create ();
Manager.update ();
Manager.delete ();
Manager.query ();
}

/**
* Add a separate line to differentiate
*/
private void Separatorline () {
System.out.println ("################################");
}

At this point, the permission checksum for query has been removed.


A simple introduction to the use of Cglib AOP functionality is done through a simulation requirement.
Cglib application is very wide, in spring,hibernate and other frameworks, is a lot of use.


Cglib principle:
Cglib Magic? In fact, once understand the principle of cglib enhancer, all the truth.
Just now in part two, there is a question: enhancer.create () exactly what object is returned.

In fact, in the previous example, Cglib generated a subclass of Infomanager dynamically during the code run, and according to the Callbackfilter accept method, All the methods in Infomanager are overridden-to perform the corresponding Methodinterceptor intercept method.

Interested friends can look at my infomanager subclass of the compiler, you can very clearly know the specific implementation. (need patience to be able to)
infomanager$ $EnhancerByCGLIB $ $de 624598.jad
Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
Jad Home page:http://www.geocities.com/kpdus/jad.html
Decompiler Options:packimports (3)
Source File Name: <generated>

Package cn.eulic.codelab.cglib;

Import Java.lang.reflect.Method;

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.