Underlying Implementation Technology of Spring AOP-JDK dynamic proxy

Source: Internet
Author: User

JDK dynamic proxy
After JDK 1.3, dynamic proxy technology is provided to allow developers to create proxy instances for interfaces at runtime. When sun launched dynamic proxy, it was hard to imagine how much it actually used. Now we finally found that dynamic proxy is an excellent underlying technology for Implementing AOP.
JDK's dynamic proxy mainly involves two classes in the Java. Lang. Reflect package: proxy and invocationhandler. Invocationhandler is an interface that defines the cross-cutting logic by implementing this interface, and calls the code of the target class through the reflection mechanism, dynamically weaving the cross-cutting logic and the business logic together.
Proxy dynamically creates a proxy instance that meets a certain interface for the invocationhandler implementation class. In this case, it must be very abstract. We will immediately start to use the proxy and invocationhandler magic rings to perform AOP-style transformation on the performance monitoring code in the previous section.
First, we delete the cross-cutting code of performance monitoring from the business class forumserviceimpl, so that forumserviceimpl is only responsible for specific business logic, as shown in:
Code List 5 forumserviceimpl: Remove performance monitoring crosstab code

Package com. baobaotao. proxy;

Public class forumserviceimpl implements forumservice {

Public void removetopic (INT topicid ){

System. Out. println ("simulate topic deletion record:" + topicid );
Try {
Thread. currentthread (). Sleep (20 );
} Catch (exception e ){
Throw new runtimeexception (E );
}

}
Public void removeforum (INT forumid ){

System. Out. println ("simulate the deletion of a Forum record:" + forumid );
Try {
Thread. currentthread (). Sleep (40 );
} Catch (exception e ){
Throw new runtimeexception (E );
}

}
}

In area ① and ② of code list 5, the original performance monitoring code is removed, and we only keep the real business logic.
Of course, you have to find a place to intercept the cross-cutting code removed from the business class. invocationhandler is the home of the cross-cutting code. We place the performance monitoring code in javasmacehandler, as shown in code list 6:
Code List 6 using macehandler

Package com. baobaotao. proxy;
Import java. Lang. Reflect. invocationhandler;
Import java. Lang. Reflect. method;

Public class implements macehandler implements invocationhandler {
Private object target;
Public writable macehandler (object target) {// ① business class with target
This.tar get = target;
}
Public object invoke (Object proxy, method, object [] ARGs)
Throws throwable {
Extends cemonitor. Begin (target. getclass (). getname () + "." + method. getname ());
Object bj = method. Invoke (target, argS); // ② call the Business Method of the target business class through the Reflection Method
Optional cemonitor. End ();
Return OBJ;
}
}

The code in the bold part is the cross-cutting code for performance monitoring. We found that the cross-cutting code only appears once, instead of the original Star. Note the method in section ②. invoke (). This statement calls the method of the target object through the reflection mechanism, so that the invocationhandler's invoke (Object proxy, method, object [] ARGs) the method is to combine the cross-cutting code with the target Business Code. Therefore, we can regard invocationhandler as the knitting machine of the business logic and cross-cutting logic. Next, we will further describe this code.
First, we implement the invocationhandler interface, which defines an invoke (Object proxy, method, object [] ARGs) method. Proxy is a proxy instance and is generally not used; A method is a method on a proxy instance. It can initiate a reflection call to the target class. ARGs is a method parameter passed through the proxy class and is used for reflection calls.
In addition, we pass in the real target object through the target in the constructor, as shown in Area ①, in the interface method invoke (Object proxy, method, object [] ARGs, pass the target class instance to method. the invoke () method calls the target class method through reflection, as shown in ②.
Next, we create a proxy instance for the forumservice interface by Using proxy and javasmacehandler, as shown in code listing 7:
Code List 7 testforumservice: Create a proxy instance

Package com. baobaotao. proxy;
Import java. Lang. Reflect. proxy;
Public class testforumservice {
Public static void main (string [] ARGs ){
Forumservice target = new forumserviceimpl (); // ① target business class
// ② Combine the target business class and cross-cutting code
Export macehandler handler = new export macehandler (target );
// ③ Create a proxy class for handler that knitting the target business logic and performance monitoring cross-cutting Logic
Forumservice proxy = (forumservice) proxy. newproxyinstance (
Target. getclass (). getclassloader (),
Target. getclass (). getinterfaces (),
Handler );
// ④ Operate the proxy instance
Proxy. removeforum (10 );
Proxy. removetopic (1012 );
}
}

The above code completes Business Code and cross-cutting code weaving and interface proxy instance generation. In section ②, We woven the forumservice instance into a performacehandler instance that contains the performance monitoring logic, then, at ③, create a proxy instance for the handler that integrates the business logic and performance monitoring logic through the static proxy method newproxyinstance, the first input parameter of this method is the class loader, and the second input parameter is a set of interfaces to be implemented by the created proxy instance, the third parameter is the braid object that integrates the business logic and the cross-cutting logic.
According to the setting method at ③, this proxy instance implements all the interfaces of the target service class, that is, the forumserviceimpl forumservice interface. In this way, we can call the proxy instance in the same way as the instance that calls the forumservice interface, as shown in ④. Run the above Code and output the following information:

Begin monitor...
Simulate the deletion of a Forum record: 10
End monitor...
Com. baobaotao. Proxy. forumserviceimpl. removeforum takes 47 milliseconds.

Begin monitor...
Simulate topic deletion: 1012
End monitor...
Com. baobaotao. Proxy. forumserviceimpl. removetopic takes 26 milliseconds.

We found that the running effect of the program is the same as that of the performance monitoring logic written directly in the business class. However, here, the original scattered cross-cutting logic code has been extracted into javasmacehandler. When performance monitoring is also required for other business methods (such as userservice and systemservice), we only need to create proxy objects for them in the preceding method. Next, we use the time sequence diagram to describe the call relationship and Further Represent the nature of the instance, as shown in 1:

Figure 1 sequence chart of the proxy instance
In particular, we use dotted line shadow to highlight the forumservice instance created through the proxy. The instance uses javasmacehandler to integrate the cross-cutting logic and business logic. When the caller calls the removeforum () and removetopic () Methods of the proxy object, the internal call sequence clearly tells us what actually happens.

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.