Java beginners how to take the first step of AOP -- use Java Dynamic proxy to implement AOP

Source: Internet
Author: User


Java beginners how to take the first step of AOP -- use Java Dynamic proxy to implement AOP
Xbird original (Participation score: 36, expert score: 90) published: Version: 1.0 read:1602Times

Current development Community The AOP (Aspect oriented programing) has been promoted, and a large number of excellent frameworks that support AOP have emerged, such as spring, Jac, and JBoss AOP. 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 is not to explain in theory what is AOP, why do you want to conduct AOP. To learn more about AOP can go to its hometown http://aosd.net to look. 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 in logging, Performance Statistics, security control, transaction processing, and other aspects. Its main intention is to record logs, performance statistics, and security control.CodeClearly divided from the business logic code, we can regard these behaviors as the problems to be solved by the system one by one, is the so-called problem-oriented programming (I wonder if it is inappropriate to translate AOP into question-Oriented Programming ). Through the separation of these behaviors, we hope that they can be configured independently into the business method, and to change these behaviors does not need 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 code. To intercept a method, we can use the callback method or dynamic proxy. Dynamic proxies are generally more flexible. Most of the AOP frameworks currently use dynamic proxies. Here we also use dynamic proxy as an example.

Jdk1.2 and later provide support for dynamic proxy,ProgramBy implementing Java. lang. reflect. the invocationhandler interface provides an execution processor and then uses Java. lang. reflect. proxy gets a proxy object that executes commercial methods. When a commercial method is called, the execution processor is 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's dynamic proxy does not directly support registering multiple invocationhandler at a time, we need to make some modifications to our business processing methods, 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 handler in turn. Fortunately, almost all AOP frameworks currently provide excellent support for this aspect.

Use spring (http://www.springframework.org /).

I am a beginner in AOP. If you are not interested in this article, you are welcome to make a brick.

Related Article

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.