The low-level implementation of AOP-cglib dynamic Proxy and JDK dynamic proxy

Source: Internet
Author: User
Tags aop object object reflection throwable
AOP is one of the core of the spring framework, and it plays a very important role in the application and is the foundation of other components of spring. It is a facet-oriented programming idea.         On the basic knowledge of AOP, I believe most of the children's shoes are already at hand, we skip this part to explain the underlying implementation mechanism of the core functions of AOP: How to use dynamic proxy to achieve cut-plane interception. The blocking capabilities of AOP are implemented by dynamic proxies in Java. To be blunt, it is to increase the slice logic on the basis of the target class, and to generate the enhanced target class (the slice logic either before the target class function executes or after the target class function executes, or when the target class function throws an exception).         The different timing of the cut corresponds to different types of interceptor, such as Beforeadviseinterceptor,afteradviseinterceptor and Throwsadviseinterceptor. So how does a dynamic proxy weave the slice logic (advise) into the target class method?         Here's a detailed introduction and implementation of the two dynamic proxies used in AOP. AOP's source code uses two kinds of dynamic agents to achieve the interception into the function: JDK dynamic proxy and cglib dynamic agent. Both methods exist at the same time, each has its advantages and disadvantages. The JDK dynamic proxy is realized by the reflection mechanism in Java, and the cglib dynamic proxy is realized by using ASM. In general, the reflection mechanism is more efficient in generating classes, and ASM is more efficient in the execution of the class after it is generated (you can solve the ASM generation class process inefficiencies by caching the ASM-generated classes). It is also important to note that the application of the JDK dynamic proxy must be the target class based on a unified interface. Without the above prerequisites, the JDK dynamic proxy cannot be applied. It can be seen that the JDK dynamic agent has some limitations, cglib this third-party library implementation of dynamic proxy application is more extensive, and more efficient in the advantages. The JDK dynamic Proxy implements AOP interception (comments are added to key points in the code)
1, for Target class (target) to define a unified interface class service, this is the JDK dynamic agent must be a prerequisite.
Package jdkproxy;

/**
 * This class is the interface class for all proxy classes, and the JDK implementation proxy requires the proxy class to be based on a unified interface
 * 
 * @author typ */public
interface Service {
	/**
	 * Add Method
	 *
	/public void Add ();

	/**
	 * Update method
	 *
	/public void update ();
}
2, the target class Aservice, our experimental goal is to aservice the add and update methods before and after the implementation of interception, add custom slice logic advise
Package jdkproxy;

/**
 * by proxy class, i.e. target category target
 * 
 * @author Typ * */Public
class Aservice implements Service { * * *
	 (non-javadoc) * * 
	 @see jdkproxy. Service#add ()
	 */public
	void Add () {
		System.out.println ("Aservice add>>>>>>> >>>>>>>>>>> ");
	}

	* * *
	 (non-javadoc) * * 
	 @see jdkproxy. Service#update ()
	 *
	/public void update () {
		System.out.println ("Aservice update>>>>> >>>>>>>>>> ");
	}
3, implement the dynamic proxy class Myinvocationhandler, realize the Invocationhandler interface, and implement the Invoke method in the interface. A closer look at the Invoke method is to add the slice logic to the method. The execution of the target class method is done by the Mehod.invoke (Target,args) statement.
Package jdkproxy;

Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;

/**
 * @author Typ * */Public
class Myinvocationhandler implements Invocationhandler {
	private Object Target;

	Myinvocationhandler () {
		super ();
	}

	Myinvocationhandler (Object target) {
		super ();
		This.target = target;
	}

	The public object invoke (object proxy, Method method, object[] args)
			throws Throwable {
		//before the execution of the program to add logic, Methodbeforeadviceinterceptor
		System.out.println ("before-----------------------------");
		Program executes
		Object result = Method.invoke (target, args);
		After the implementation of the program to add logic, Methodafteradviceinterceptor
		System.out.println ("after------------------------------");
		return result;
	}


4. Test class, in which the target object is enhanced by Proxy.newproxyinstance (Aservice.getclass (). getClassLoader (), Aservice.getclass (). getinterfaces (), handler);
package jdkproxy;

Import Java.lang.reflect.Proxy; /** * @author Typ * * * * * */public class Test {public static void main (string[] args) {Service aservice = new Aservice (
		);
		Myinvocationhandler handler = new Myinvocationhandler (aservice); Proxy dynamically creates a proxy instance Service Aserviceproxy = (service) proxy.newproxyinstance (Aservice. GE) that conforms to an interface for the Invocationhandler implementation class.
		Tclass (). getClassLoader (), Aservice.getclass (). Getinterfaces (), handler);
		The proxy execution program is aserviceproxy by dynamically generated proxy object, in which aserviceproxy conforms to the Service Interface Aserviceproxy.add ();
		System.out.println ();
		Aserviceproxy.update ();
		The following is a proxy for b/Service bservice = new bservice ();
		Myinvocationhandler handler = new Myinvocationhandler (bservice); Service Bserviceproxy = (service) proxy.newproxyinstance (bservice//. GetClass (). getClassLoader (),
		Bservice.getclass ()//. Getinterfaces (), handler);
		Bserviceproxy.add ();
		System.out.println ();
	Bserviceproxy.update (); }
}
Since then, the JDK dynamic Proxy to implement the AOP interception mechanism code has been implemented, we look at the results of the interception, the program output is as follows: Before-----------------------------Aservice add>>> >>>>>>>>>>>>>>> after------------------------------ Before-----------------------------Aservice update>>>>>>>>>>>>>>> After------------------------------
As you can see, the AOP interception mechanism is in effect after the Add and update methods of the target class Aservice have been added to the custom slice logic.

Ii. cglib Dynamic Proxy implementation of AOP interception (comments are added to key points in the code)
1, the target class, Cglib does not need to define the target class uniform interface
Package cglibproxy;

/**
 * is a proxy class, i.e. target object target
 * 
 * @author Typ * */Public
class Base {
	/**
	 * A simulated Add method
	 */Public
	void Add () {
		System.out.println ("Add------------");
	}

2, realize the dynamic proxy class Cglibproxy, need to realize methodinterceptor interface, realize intercept method. In this proxy, the custom slice logic is added before and after the Add method, and the target class Add method executes the statement as Proxy.invokesuper (object, args);
Package cglibproxy;

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

/**
 * This is the proxy class for adding advise
 * 
 * @author typ * */
 public
class Cglibproxy implements in Pointcut Methodinterceptor {Public

	object intercept (Object object, method method, object[] args,
			methodproxy proxy) Throws Throwable {
		//Add slice logic (advise), which is methodbeforeadviceinterceptor before the target class code executes.
		System.out.println ("before-------------");
		Executes the target class Add method
		Proxy.invokesuper (object, args);
		Add slice logic (advise), which is methodafteradviceinterceptor after the target class code executes.
		System.out.println ("after--------------");
		return null;
	}

}
3, get the enhanced target class of the factory factory, where the Enhanced method class object is enhancer to implement, the code looks like this:
Package cglibproxy;

Import Net.sf.cglib.proxy.Enhancer;

/**
 * Factory class, Generate enhanced target class (joined into logic)
 * * 
 @author Typ * */Public
class Factory {
	/**
	 * Gets the target class after the enhancement, that is, the target class after the logical advice is added
	 * * 
	 @param proxy
	 * @return/public
	static Base getinstance (Cglibproxy proxy) {
		enhancer enhancer = new enhancer ();
		Enhancer.setsuperclass (base.class);
		The parameter of the callback method is the proxy class object Cglibproxy, and finally The Intercept method
		enhancer.setcallback (proxy)
		in the proxy class object Cglibproxy is enhanced by the target class invocation. At the moment, base is not a pure target class, but an enhanced target class
		base = (base) enhancer.create ();
		return base;
	}
4. Test class
Package cglibproxy;

/**
 * @author Typ * * * * *
 /Public
class Test {public
	static void Main (string[] args) {
		Cglibproxy proxy = new Cglibproxy ();
		Base base
		= Factory.getinstance (proxy) for the generated enhanced target class;
		Base.add ();
	}

Since then, cglib dynamic Proxy implementation of the AOP interception mechanism has been basically implemented, let's take a look at the effect of interception, the results of the program implementation is as follows:
Before-------------add------------after--------------you can see that the AOP interception mechanism is in effect after the Add method of the target class base has been added to the custom slice logic.
Also, it needs to be explained that the Cglib dynamic Proxy uses a Third-party class library that requires the introduction of two jar packages in the project: Cglib.jar and Asm.jar. The two jar packages will be uploaded later in the CSDN resource. Free of points ah. Jar packages and related code see http://download.csdn.net/detail/dreamrealised/6427885
In short, the core mechanism and basic functions of AOP have been implemented through dynamic proxies, as for AOP, how to get target class targets, advisor beans from configuration documents, how to judge interceptor types, and so on, is solved with the help of another core IOC in spring. The following will be explained by the core implementation mechanism of the IOC.

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.