Use Java Dynamic proxy to implement AOP

Source: Internet
Author: User

Currently, the entire development community
Programing) has been promoted, and a large number of excellent frameworks supporting AOP have emerged, such as spring, Jac, and JBoss AOP.
And so on. AOP seems to be a trend for a while. Java beginners can't help but feel deeply that OOP has not been able to learn it, and it has come to AOP. This article does not explain in theory what is AOP,
Why do we need to conduct AOP. Learn more about AOP can go to its hometown http://aosd.net
Go. Here is just a simple example to show beginners how to implement AOP.
For the sake of simplicity, the example does not use any third-party AOP framework, but uses the dynamic proxy feature inherent in the Java language to implement AOP.
Let's go back to AOP. AOP is mainly used for logging, performance statistics, and security.
Control
System and transaction processing. Its main intention is to clearly classify the log records, Performance Statistics, security control, and other codes from the commercial logic code. We can regard these behaviors as a system one by one.
The problem to be solved is the so-called problem-oriented programming (I do not know whether it is inappropriate to translate AOP into problem-oriented programming ). By separating these behaviors, we hope that they can be configured independently to business methods.
To change these behaviors does not have to affect the business method code.

Assume that the system has completed the business logic functions by a series of businessobject, and the system requires that the log be recorded every time the business logic is processed. The specific business logic code is omitted here.

Public interface businessinterface {
Public void processbusiness ();
}
Public class businessobject implements businessinterface {
Private logger = logger. getlogger (this. getclass (). getname ());
Public void processbusiness (){
Try {
Logger.info ("start to processing ...");
// Business logic here.
System. Out. println ("Here is business logic ");
Logger.info ("End Processing ...");
} Catch (exception e ){
Logger.info ("exception happends ...");
// Exception Handling
}
}
}
The code that processes the business logic and the log record code are mixed here, which brings some difficulties to future maintenance and may cause a lot of code duplication. The identical Log Code will appear in every businessobject of the system.


According to the idea of AOP, we should separate the log record code. To separate these codes involves a problem. We must know when the commercial logic code will be called, so that we can insert the log record generation.
. To intercept a method, we can use the callback method or dynamic proxy. Dynamic proxy is generally more flexible. Currently, most of the AOP
Most frameworks adopt Dynamic proxies. Here we also use dynamic proxy as an example.


JDK and later provide support for dynamic proxies. Programmers provide an execution process by implementing the java. Lang. Reflect. invocationhandler interface.
And then get a proxy object through java. Lang. Reflect. Proxy. This proxy object is used to execute commercial methods. When a commercial method is called, the execution processor will
Automatically called.

With JDK, all we have to do is provide a log processor.

Public class loghandler implements invocationhandler {
Private logger = logger. getlogger (this. getclass (). getname ());
Private object delegate;
Public loghandler (Object delegate ){
This. Delegate = delegate;
}
Public object invoke (Object proxy, method, object [] ARGs) throws throwable {
Object o = NULL;
Try {
Logger.info ("method stats..." + method );
O = method. Invoke (delegate, argS );
Logger.info ("method ends..." + method );
} Catch (exception e ){
Logger.info ("exception happends ...");
// Excetpion handling.
}
Return O;
}
}
Now we can remove all the log processing code in businessobject.

Public class businessobject implements businessinterface {
Private logger = logger. getlogger (this. getclass (). getname ());
Public void processbusiness (){
// Business processing
System. Out. println ("Here is business logic ");
}
}
The code for the client to call a commercial method is as follows,
Businessinterface businessimp = new businessobject ();
Invocationhandler handler = new loghandler (businessimp );
Businessinterface proxy = (businessinterface) proxy. newproxyinstance (
Businessimp. getclass (). getclassloader (),
Businessimp. getclass (). getinterfaces (),
Handler );
Proxy. processbusiness ();
The program output is as follows:

Info: Method stats...
Here is business logic
Info: Method ends...
So far, our first small attempt is complete. We can see that after using AOP, the logging and business logic code are completely separated.
In the future, you only need to modify the log record processor, and the business object itself (businessobject) does not need to be modified. In addition, this log record will not cause repeated code. All commercial processing objects can reuse this log processor.


Of course, in actual application, this example is too rough. Because JDK dynamic proxy does not directly support registering multiple invocationhandler at a time
This method requires both logging and Performance Statistics. Generally, we can define a handler interface and maintain a queue to store all handler,
When invocationhandler is triggered, we call our own handler in turn. Fortunately, almost all of the current AOP
Framework provides good support for this. Here we recommend that you use spring (http://www.springframework.org/
).

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.