The underlying implementation technology of Spring AOP---jdk dynamic agent

Source: Internet
Author: User

JDK Dynamic Agent
The dynamic Agent technology is provided after JDK 1.3, allowing the developer to create proxy instances of the interface at run time. When Sun just launched its dynamic agent, it was hard to imagine how much it would actually do, and now we finally find that dynamic proxies are the perfect bottom-up technology for AOP.
The dynamic agent of the JDK mainly involves the two classes in the Java.lang.reflect package: Proxy and Invocationhandler. Where Invocationhandler is an interface that can define crosscutting logic by implementing the interface, and invoke the code of the target class through the reflection mechanism to dynamically weave the crosscutting logic and the business logic together.
The proxy for the Invocationhandler implementation class dynamically creates a broker instance that conforms to an interface. This must be very abstract, we immediately began to use proxy and invocationhandler these two magic rings the performance monitoring code in the previous section of the AOP-style transformation.
First, we remove the crosscutting code for performance monitoring from the business class Forumserviceimpl, so that Forumserviceimpl is only responsible for the specific business logic, as shown in:
Code Listing 5 Forumserviceimpl: Removing performance monitoring crosscutting code

[Java]View Plaincopy
  1. Package com.baobaotao.proxy;
  2. Public class Forumserviceimpl implements Forumservice {
  3. public void removetopic (int topicid) {
  4. System.out.println ("Simulated deletion of topic records:" +topicid);
  5. try {
  6. Thread.CurrentThread (). Sleep (20);
  7. } catch (Exception e) {
  8. throw New RuntimeException (e);
  9. }
  10. Ii
  11. }
  12. public void Removeforum (int forumid) {
  13. System.out.println ("simulated delete forum record:" +forumid);
  14. try {
  15. Thread.CurrentThread (). Sleep (40);
  16. } catch (Exception e) {
  17. throw New RuntimeException (e);
  18. }
  19. Ii
  20. }
  21. }

In code Listing 5, ① and ②, the original performance monitoring code was removed, and we kept only the real business logic.
Crosscutting code removed from the business class of course we have to find a place to stay, Invocationhandler is the homeland of the crosscutting code, and we place the code for performance monitoring in Performacehandler, as shown in Listing 6:
Code Listing 6 Performacehandler

[Java]View Plaincopy
  1. Package com.baobaotao.proxy;
  2. Import Java.lang.reflect.InvocationHandler;
  3. Import Java.lang.reflect.Method;
  4. Public class Performacehandler implements Invocationhandler {
  5. private Object target;
  6. Public Performacehandler (object target) {//①target as the target business class
  7. = target;
  8. }
  9. Public object Invoke (Object proxy, Method method, object[] args)
  10. throws Throwable {
  11. Performancemonitor.begin (Target.getclass (). GetName () +"."  + Method.getname ());
  12. Object BJ = Method.invoke (target, args); //② Calling the business method of the target business class through the reflection method
  13. Performancemonitor.end ();
  14. return obj;
  15. }
  16. }

The code for the Bold section is the crosscutting code for performance monitoring, and we find that the crosscutting code appears only once, not the original. Attention is paid to the Method.invoke () at ②, which invokes the method of the target object through a reflection mechanism, so that the Invocationhandler invoke (object proxy, method, object[] args) Method weaves the Crosscutting code and the target business class code together, so we can consider Invocationhandler as a weaver of business logic and crosscutting logic. Let's take a closer note of this piece of code.
First, we implement the Invocationhandler interface, which defines a method for invoke (Object Proxy, method, object[] args), which is a proxy instance and is not typically used The method is a way on the proxy instance that can initiate a reflection call to the target class, which is used by the method arguments passed in by the proxy class when the reflection is invoked.
In addition, we pass the target in the constructor to the real target object, as shown in ①, in the interface method invoke (Object proxy, method, object[] args), the object class instance is passed to Method.invoke () Method that invokes the target class method through reflection, as shown in ②.
Below, we create a proxy instance of the Forumservice interface by using Proxy with Performacehandler, as shown in Listing 7:
Code Listing 7 Testforumservice: Creating a proxy instance

[Java]View Plaincopy
  1. Package com.baobaotao.proxy;
  2. Import Java.lang.reflect.Proxy;
  3. Public class Testforumservice {
  4. public static void Main (string[] args) {
  5. Forumservice target = new Forumserviceimpl (); ① target Business class
  6. ② Weaving the target business class and the crosscutting code together
  7. Performacehandler handler = new Performacehandler (target);
  8. //③ creates a proxy class for handler that weaves the target business class logic and performance monitoring crosscutting logic
  9. Forumservice proxy = (forumservice) proxy.newproxyinstance (
  10. Target.getclass (). getClassLoader (),
  11. Target.getclass (). Getinterfaces (),
  12. handler);
  13. //④ Action Agent Instance
  14. Proxy.removeforum (10);
  15. Proxy.removetopic (1012);
  16. }
  17. }

The code above completes the work of Business class code and cross-cutting code weaving and interface broker instance generation, where at ② we weave the Forumservice instance into a Performacehandler instance that contains the performance monitoring logic, and then at ③, The static method of proxy newproxyinstance () creates a proxy instance of the Forumservice interface for handler that incorporates the business class logic and performance monitoring logic, and the first entry of the method is the class loader, The second entry is a set of interfaces to be implemented by the proxy instance that is created, and the third parameter is the Braid object that consolidates the business logic and the crosscutting logic.
According to ③, this proxy instance implements all the interfaces of the target business class, that is, the Forumserviceimpl Forumservice interface. This allows us to invoke the proxy instance in the same way that an instance of the Forumservice interface is called, as shown in ④. Run the above code and output the following information:

[Java]View Plaincopy
    1. Begin Monitor ...
    2. Demo Delete Forum record:Ten
    3. End Monitor ...
    4. Com.baobaotao.proxy.ForumServiceImpl.removeForum takes 47 milliseconds.
    5. Begin Monitor ...
    6. Simulated Delete topic record:1012
    7. End Monitor ...
    8. Com.baobaotao.proxy.ForumServiceImpl.removeTopic takes 26 milliseconds.

We found that the effect of the program was consistent with writing performance monitoring logic directly in the business class, but here the original scattered crosscutting logic code has been extracted into the performacehandler. When the business methods of other business classes (such as UserService, Systemservice, etc.) also need to use performance monitoring, we just have to create proxy objects for each of them in the same way. Below, we use time series diagrams to describe the invocation relationship, further the nature of the proxy instance, as shown in 1:

Figure 1 Timing diagram of the proxy instance
In particular, we highlight the Forumservice instance created through the proxy in a way that uses the Performacehandler to consolidate crosscutting logic and business logic, especially with dashed shadows. When the caller invokes the Removeforum () and Removetopic () methods of the proxy object, the internal invocation timing clearly tells us what actually happened.

The underlying implementation technology of Spring AOP---jdk 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: 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.