"Spring" AOP jdk dynamic agent and Cglib dynamic agent

Source: Internet
Author: User
Tags throwable

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

First, the Java Dynamic Agent
1.1 Proxy Mode
Proxy mode is a common Java design pattern, his characteristic is that the proxy class and the delegate class have the same interface, the proxy class is mainly responsible for the delegate class preprocessing messages, filtering messages, forwarding messages to the delegate class, and post-processing messages. There is usually an association between the proxy class and the delegate class, and the object of a proxy class is associated with an object of a delegate class, and the object of the proxy class does not actually implement the service, but instead provides a specific service by invoking the related method of the object of the delegate class.
The proxy class can be divided into two types according to the agent's creation period.
Static proxy: The source code is generated automatically by the programmer or a specific tool, and then compiled. Before the program runs, the. class file for the proxy classes already exists.

Dynamic Agent: When the program is running, it is created dynamically using the reflection mechanism.

We know that by using proxies, you can add some processing methods to the methods of the Proxied class, which results in an AOP-like effect. The dynamic proxy provided in the JDK is a very low-level technology to implement AOP.


1.2 JDK Dynamic Agent

The JDK dynamic agent mainly involves two classes in the Java.lang.reflect package: Proxy and Invocationhandler. Invocationhandler is an interface that dynamically compiles crosscutting logic and business logic by implementing the interface to define crosscutting logic and invoking the code of the target class through a reflection mechanism.
Proxy uses Invocationhandler to dynamically create an instance that conforms to an interface, generating a proxy object for the target class.
1.3 Cglib Dynamic Agent

There is also a dynamic agent called Cglib, cglib all called Code Generation Library, is a powerful high-performance, high-quality code generation Class library, you can extend Java class and implement Java interface at runtime, Cglib encapsulates ASM, The new class can be dynamically generated during the run-time period. Compared to the JDK dynamic agent: The JDK Creation Agent has a limitation that only proxy instances can be created for the interface, and for classes that do not have a business method defined through the interface, dynamic proxies are created through Cglib


(The following code comes from spring.3.x Enterprise application development Practice, some of which the author has made some additions)

Second, the JDK dynamic agent

1, Interface Forumservice

Package Aop;public interface Forumservice {public void removetopic (int topic);p ublic void removeforum (int forumid);}
2, Forumserviceimpl realization

Package Aop;public class Forumserviceimpl implements forumservice{public void removetopic (int topic) { SYSTEM.OUT.PRINTLN ("Simulated delete record" +topic); Try{thread.currentthread (). Sleep (20);} catch (Exception e) {throw new RuntimeException (e);}} public void Removeforum (int forumid) {System.out.println ("simulated delete record" +forumid), Try{thread.currentthread (). Sleep (20);} catch (Exception e) {throw new RuntimeException (e);}}}
Here we can take a look at the above method:

Test first:

Forumserviceimpl forumserviceimpl=new Forumserviceimpl (); Forumserviceimpl.removeforum (190); Forumserviceimpl.removetopic (123);

Next we want to add some methods before and after deleting the records

3. The enhancement method to be inserted in the Forumserviceimpl.java

Package Aop;public class PerformanceMonitor {private static threadlocal<methodperformance> performancerecord= New Threadlocal<methodperformance> ();p ublic static void Begin (String method) {System.out.println ("Begin monitor .."); Methodperformance mp=new methodperformance (method);p Erformancerecord.set (MP);} public static void End () {SYSTEM.OUT.PRINTLN ("End monitor ..."); Methodperformance mp=performancerecord.get (); Mp.printperformance ();}}

Methodperformance.java is really the way to join

Package Aop;public class Methodperformance {Private long begin;private long end;private String servicemethod;public metho Dperformance (String servicemethod) {    this.servicemethod=servicemethod;    This.begin=system.currenttimemillis ();} public void Printperformance () {    end=system.currenttimemillis ();    Long Elapse=end-begin;    


4. JDK Dynamic Agent Performancehandler.java

Package Aop;import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;public class Performancehandler implements Invocationhandler {Private Object Target;public Performancehandler (Object object) { This.target = object;} @Overridepublic object Invoke (Object arg0, Method arg1, object[] arg2) throws Throwable {Performancemonitor.begin ( Target.getclass (). GetName () + "." + Arg1.getname ()); Object obj = Arg1.invoke (target, arg2); Performancemonitor.end (); return obj;}}

5. Use

Forumserviceimpl target=new Forumserviceimpl (); Performancehandler handler=new Performancehandler (target); Forumservice proxy= (Forumservice) proxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getClass (). Getinterfaces (), handler);p Roxy.removeforum ();p roxy.removetopic (678); SYSTEM.OUT.PRINTLN ("End monitor ...");

Results:


Third, cglib dynamic agent

1, Cglibproxy.java

Package Aop;import Java.lang.reflect.method;import Org.springframework.cglib.proxy.enhancer;import Org.springframework.cglib.proxy.methodinterceptor;import Org.springframework.cglib.proxy.methodproxy;public Class Cglibproxy implements Methodinterceptor{private  enhancer enhancer=new enhancer ();p ublic Object GetProxy ( Class clazz) {enhancer.setsuperclass (clazz); Enhancer.setcallback (this); return Enhancer.create ();} @Overridepublic Object Intercept (object arg0, Method arg1, object[] arg2,methodproxy arg3) throws Throwable {Performancem Onitor.begin (Arg0.getclass (). GetName () + "." + Arg1.getname ()); Object obj = Arg3.invoke (arg0, arg2); Performancemonitor.end (); return obj;}}
2. Testing

Cglibproxy proxy2=new cglibproxy (); Forumserviceimpl forumserviceimpl= (Forumserviceimpl) proxy2.getproxy (Forumserviceimpl.class); Forumserviceimpl.removeforum (456); Forumserviceimpl.removetopic (987); SYSTEM.OUT.PRINTLN ("End monitor ...");
3. Results:


Four, the JDK dynamic agent and Cglib comparison

The performance of dynamic proxy objects created by Cglib is much higher than the performance of the proxy objects created by the JDK, about 10 times times, but cglib the time it takes to create a proxy object is about 8 times times more than the JDK dynamic agent, so for singleton proxy objects or agents with instance pools, Because there is no need to create new instances frequently, it is more suitable for cglib dynamic agent technology, whereas the other is applicable to JDK dynamic agent technology. In addition, because Cglib generates proxy objects in a way that dynamically creates subclasses, it is not possible to process methods such as final,private in the target class. Therefore, we need to choose what kind of agent to use according to the actual situation. Similarly, the relevant Proxyfactory agent factory in spring's AOP programming is using the JDK dynamic agent or cglib dynamic proxy, and the enhancement (advice) is applied to the target class through dynamic proxies.

Lin Bingwen Evankaka Original works. Reprint please specify the source Http://blog.csdn.net/evankaka

"Spring" AOP jdk dynamic agent and 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.