Currently, the entire development community is focusing on AOP (Aspect Oriented Programing), and a large number of excellent frameworks that support AOP, such as Spring, JAC, and Jboss AOP, have emerged. 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 clearly divide the log records, Performance Statistics, security control, and other codes from the commercial 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 = 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.