Spring AOP Implementation principle (i) AOP using AspectJ's compile-time enhancements

Source: Internet
Author: User

AOP (Aspect Orient programming), which is aspect-oriented programming, is a complement to object-oriented programming and is designed to be used in processing systems that are distributed across modules (in different ways)

Cross-focus issues in Java in EE applications, AOP is often used to process some system-level services with crosscutting properties, such as transaction management, security full check, cache, object pool management, and more. AOP

implementation of The key is that the AOP framework automatically creates an AOP proxy, The AOP agent is mainly divided into static agent and dynamic Agent . In two categories, static proxies are represented by AspectJ, while dynamic agents are

Spring AOP is represented. This article will begin with AspectJ analysis, and introduce CGLIB to introduce the implementation principle of Spring AOP framework.


AOP (Aspect Orient programming), as a complement to object-oriented programming, is widely used to deal with some system-level services with crosscutting properties, such as transaction management safety, security, mitigation ,

storage, Object pool management, and more. the key to AOP is that the AOP framework automatically creates the AOP proxy, and the AOP agent can be divided into static agent and dynamic agent, in which the static agent refers to the use of

AOP Box the commands provided by the rack are compiled so that they can be into an AOP proxy class, so also known as compile-time while dynamic proxies are running with the help of the JDK dynamic proxy cglib

"temporary" generation of AOP dynamic generation in memory also known as run-time enhancements.


The existence value of AOP


In traditional OOP programming, with objects as the core, the entire software system consists of a series of interdependent objects that are abstracted into a single class and allow class inheritance to be used to manage classes and

General to special relationships between classes. with the increase of software scale and the gradual upgrading of application, there are some problems that OOP is difficult to solve.


we can analyze, abstract a series of objects with certain attributes and behavior, and through the collaboration between these objects to form a complete software function. Because objects can inherit, we

can have the same function or the same attribute attributes are abstracted into a hierarchical class structure system. With the continuous expansion of software specifications, professional Division of labor More and more series, as well as OOP application practice

, it also exposes some of the things that OOP cannot solve. problem.


now assume that the system has 3 pieces of completely similar code, the code will usually be "copy", "Paste" way to complete, through the "copy", "Paste" the way developed by the soft as shown in piece 1.


As seen in 1, the possible readers have found the disadvantage of this approach: if one day, the dark code snippet in Figure 1 needs to be modified, is it not to open a 3-place

code to modify? What would happen if the code was not included in 3 places, but in 100 places or even 1000 places ?


To solve this problem, we typically define the dark code portion of 1 as a method, and then call the method separately in 3 code snippets. In this way, the software

The structure of the system is shown in 2.


for the software system shown in 2, if you need to modify the dark part of the code, just modify a place, no matter how many places in the whole system called the method, The program does not need to modify these

Place, just modify the called Party method Can--in this way, greatly reduces the complexity of the software later maintenance.


For Method 1, Method 2, and Method 3 shown in 2, it is still necessary to explicitly call the Dark method, which will solve most of the scenarios. But for some of the more special situations: The application requires methods

1, Method 2, Method 3 thoroughly and Dark Method Separation--Method 1, Method 2, Method 3 does not need to call the dark method directly, how to solve?


Because the software system requirements change is very frequent thing, the system pre-design Method 1, Method 2, Method 3 only realized the core business functions, after a period of time, we need for Method 1, method

2. Method 3 increases transaction control After a period of time, the customer proposed Method 1, Method 2, Method 3 needs to authenticate the user's legitimacy, only users of the law can execute these methods;

for some time, the customer also proposed method 1, Method 2, Method 3 the logging should be increased; another period of time, the customer also mentioned out of the ... In the face of such a situation, what do we do? There are usually two ways to do

Method:

    • Directly reject customer requirements according to the requirement specification.
    • Embrace the needs and meet the needs of our customers.

The first approach is obviously not good, the customer is God, we should try to meet the needs of customers. It usually takes the second approach, how to solve it? is not every time you define a new method and then modify

Method 1, Method 2, Method 3, add new method to call? This is not a small amount of work! We would like to have a special approach: we just need to define the method, not in Method 1, Method 2, Square

in Method 3, the system will "automatically" execute the special method.


The idea sounds magical, even somewhat impractical, but it's completely achievable, and the technology to achieve this is AOP. AOP is dedicated to processing systems that are distributed across modules

cross-off in (different methods) point of issue, in Java EE applications, it is common to use AOP to process some system-level services with crosscutting properties such as transaction management, security checks, caching,

like pool management, AOP has become a very common solution case.


Using AspectJ's compile-time enhancements for AOP


AspectJ is a Java-based AOP framework that provides powerful AOP capabilities, and many other AOP frameworks draw on or adopt some of these ideas.


AspectJ is an AOP implementation of the Java language, which consists of two parts: The first section defines how to express and define the syntax specification in AOP programming, through which set of language specifications, we

It is easy to use AOP to solve A cross-concern problem in the Java language; the other part is the Tools section, including the compiler, debugging tools and so on.

AspectJ is one of the earliest and powerful AOP implementations, which has a good implementation of the whole set of AOP mechanisms, and many other languages are implemented in AOP, which also draws on or incorporates Many of the AspectJ are set

of the meter. In the Java realm,Many of the grammatical structures in AspectJ have been largely the norm in the field of AOP.


Download, install AspectJ is relatively simple, the reader login AspectJ official website (HTTP://WWW.ECLIPSE.ORG/ASPECTJ), you can download to an executable JAR package, using Java-jar aspectj-

1.x.x.jar command, multiple orders Click the "Next" button to successfully install the AspectJ.


After successfully installing AspectJ, you will see the following file structure under the E:\Java\AOP\aspectj1.6 path (AspectJ installation path):

    • Bin: This path holds the AJ, Aj5, AJC, Ajdoc, ajbrowser commands, where the AJC command is most commonly used, it acts like a javac, and is used to compile-time enhancements to ordinary Java classes.
    • Docs: This path contains AspectJ instructions, reference manuals, API documentation, and more.
    • Lib: the 4 JAR files under this path are the core class libraries of AspectJ.
    • The relevant authorization file.

Some documents, AspectJ primer Books, when it comes to using AspectJ, think that you must use the Eclipse tool, and it seems that you cannot use AspectJ without the tool.


Although AspectJ is an open source project for the Eclipse Fund and provides the eclipse AJDT plug-in (AspectJ development Tools) to develop AspectJ should use, but AspectJ

absolutely no need to rely on Eclipse tools.


In fact, AspectJ is very simple to use, just as we compile and run Java programs with the JDK. The following is a simple procedure to demonstrate the use of AspectJ and analyze AspectJ

How to make enhancements at compile time.


Start by writing a simple Java class that simulates a business component.

public class Hello {//define a simple method that simulates the business logic method in the application public void SayHello () {System.out.println ("Hello aspectj!");} The main method, the entry of the program public static void Main (string[] args) {Hello h = new Hello (); H.sayhello ();}  }

The above Hello class simulates a business logic component, compiles, runs the Java program, the result is no suspense, the program will print in the console "Hello AspectJ "string.


Suppose that now the customer needs to start the transaction before executing the SayHello () method, and when the execution of the method closes the transaction, in traditional programming mode we must manually modify SayHello () method-such as

use AspectJ instead, You may not need to modify the SayHello () method above.

Here we define a special Java class.

Public aspect Txaspect {  //Specifies execution of the Hello.sayhello () method when executing the following code block void around (): Call (void Hello.sayhello ()) { System.out.println ("Start transaction ...");p roceed (); System.out.println ("End of Transaction ...");}

Perhaps the reader has discovered that the above class file does not use class, interface, enum to define the Java class, but instead uses aspect--is the Java language new added a keyword? Didn't

there! The txaspect above is not a Java class at all, so aspect is not a Java-supported keyword, it's just a keyword that AspectJ can recognize .


The bolded code above is also not a method, it just specifies that when the program executes the SayHello () method of the Hello object, the system will instead execute the curly brace code block of the bold code, where the proceed () generation

Table Callback original SayHello () method.


As mentioned earlier, Java does not recognize the contents of the Txaspect.java file, so we will use the Ajc.exe command to compile the above Java program. In order to be able to use Ajc.exe at the command line

The bin path under the AspectJ installation directory (more than E:\Java\AOP\aspectj1.6\bin directory) added to the system's PATH environment variable the.

Next, execute the following command to compile:

Ajc-d. Hello.java Txaspect.java

we can interpret Ajc.exe as Javac.exe command, which is used to compile Java programs, except that the Ajc.exe command can recognize AspectJ syntax; we can put Ajc.exe

as an enhanced version of javac.exe command.

The program runs the Hello class using the following command:

Java Hello

Run the program and you'll see a surprising result:

Start a transaction ... Hello aspectj! Transaction End ...

from the results of the above operation, we can not make any changes to the Hello.java class, but also to meet customer needs: The above program is only in the console print "Open The beginning of the transaction ... "," End

transaction ... "To simulate the transaction , we can actually replace these two simple statements with the actual transaction operation code, which will meet the needs of the customer I beg of you.


If the customer is proposing new requirements again, it is very simple to add the logging function after the SayHello () method, and then we define a logaspect with the following procedure:

Public aspect Logaspect {/* defines a PointCut, which is named logpointcut*//* the PointCut method that corresponds to the specified Hello object SayHello */pointcut ( ): Execution (void Hello.sayhello ()); /* After logpointcut execute the following code block */after (): Logpointcut () {System.out.println ("Logging ...");}}

The bold code of the above program defines a pointcut:logpointcut-equivalent to the SayHello () method that executes the Hello object, and specifies that a simple block of code is executed after logpointcut.

In other words, the SayHello ()

Method executes the specified code block after the Use the following command to compile the above Java program:

Ajc-d. *.java

Run the Hello class again and you will see the following running results:

Start a transaction ... Hello aspectj! Logging ... End of transaction ...


Judging from the results above, we can add new functionality to the SayHello () method by using the AOP support provided by AspectJ.

Why does the Hello class constantly and dynamically add new functionality without any modification to the Hello class? This does not seem to conform to the basic Java grammar rules.

In fact, we can use the Java Anti-compilation tool to reverse compile the Hello.class file generated by the previous program and find the code for the Hello.class file as follows:

Import Java.io.printstream;import Org.aspectj.runtime.internal.aroundclosure;public class Hello{public  void SayHello () {    System.out.println ("Hello aspectj!");  }  public static void Main (string[] args) {    Hello h = new Hello ();    Hello localHello1 = h; Sayhello_aroundbody1$advice (LocalHello1, txaspect.aspectof (), null);  }   private static final void Sayhello_aroundbody0 (Hello paramhello) {Paramhello.sayhello ();  }  private static final void Sayhello_aroundbody1$advice (Hello target, Txaspect ajc$aspectinstance, Aroundclosure ajc$ Aroundclosure) {    System.out.println ("Start transaction ...");    Aroundclosure localaroundclosure = ajc$aroundclosure;    Sayhello_aroundbody0 (target);    System.out.println ("End of Transaction ...");}  

It is not difficult to find this Hello.class file is not compiled by the original Hello.java file, the Hello.class added a lot of content-this shows that AspectJ in the "Auto" compiled when translated

to a new class, this new class enhanced the functionality of the original Hello.java class, so AspectJ is often referred to as a compile-time enhanced AOP framework.


tip: In contrast to AspectJ, there is another AOP framework that does not need to be enhanced at compile time for the target class, but instead generates a proxy class for the target class at run time, the generation Class or the target class

implement the same interface, either subclass of the target class-in short, an instance of the proxy class can be used as an instance of the target class. In general, the enhanced AOP framework at compile time has a better performance advantage

--because the runtime dynamically enhanced AOP framework requires every run -time are dynamically enhanced.


In fact, AspectJ allows Add new features to multiple methods at the same time, as long as we specify more methods to match when we define Pointcut. The following fragment:

Pointcut xxxpointcut (): Execution (void h*.say* ());

The xxxpointcut in the above program will be able to match all of the classes starting with H, all of the methods beginning with say, but the method must return void; If you do not want to match any type of return value,

You can change the code to the following form Type:

Pointcut xxxpointcut (): Execution (* h*.say* ());

For information on how to define Aspect, Pointcut, etc. in AspectJ, readers can refer to the Quick5.pdf file in the doc directory under the AspectJ installation path.



Spring AOP Implementation principle (i) AOP using AspectJ's compile-time enhancements

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.