The basic principles of AOP design of spring design thought

Source: Internet
Author: User

0. Preface

Spring provides support for AOP (Aspect oriented programming), so what is AOP? This article will explain the concept of AOP in a different perspective to help you better understand and use spring AOP.


After reading this article, you will learn:
1. Java program execution characteristics in the JVM
2. Run stream for Java programs "understand the concepts of AOP, Connection points (join point), Pointcut (Point cut)"
3. Introduction of the agent-mode Java program run Stream (mechanism of AOP implementation)
4. How Spring AOP Works


1. Java program execution characteristics in the JVM

When we write a main () method in a class Foo, and then run java foo, your Java program's journey is turned on, such as the following:

public class Foo {public    static void Main (string[] args) {        //Your codes begins here}    }

So in the process of running this. What did the JVM do for you?

When you run Java Foo , the JVM creates a main thread, main thread, which takes the main () method above as the portal. Start running your code.

Each thread maintains its own stack (stack) in memory, documenting the process in which the entire program runs. Each element in the stack is called a stack frame, and the stack frame represents a method call that records the information of the method call; In fact, when we call a method in the code, we have a stack frame in memory corresponding to the stack and the stack.

about virtual machine line stacks (JVM Stack)
The model for virtual machine line stacks (JVM thread Stack) is not the focus of this article. So it's not going to unfold here, and the reader is able to view one of my other posts, which is covered in detail.

Java Virtual machine schematic 3, JVM execution time data area]

At a particular point in time, a stack within a main thread renders, for example, what is seen:


From a line stacks point of view, we can see that the basic unit of the JVM handling Java programs is 方法调用 . As a matter of fact. The instruction of the most basic unit that the JVM runs (that is, atomic operations) is a machine bytecode of assembly-language nature.

The reason 方法调用 for this is that the basic operating unit of the Java program is viewed from a more macroscopic perspective.

How do I get to the contents of the virtual Machine line stacks (that is, the method call procedure)?

Just imagine. How can I get the contents of a method call to the JVM line stacks? I believe that all Java programmer know the answer. Java programmer almost every day to see it------when our code throws an exception and does not catch or execute when an error occurs . We're going to get a nasty log message like this:




of course, in addition to the code throws an exception, we can still detect other ways contents of the JVM line Cheng . ability to pass the Thread.dumpstack () method create a fake exception instance, and then exception the current thread of this instance record The contents of the stack are output to the standard error stream。 likeI ran it somewhere in the code. Thread.dumpstack () method, output results such as the following:



2. Java program run Flow "Understanding the concepts of AOP, Connection points (join point), Pointcut (Point cut)"
Assuming that the Java program is running from the perspective of the virtual machine line stacks, you will find that the process of running the program is the process of method invocation.

We line up the method calls in the order in which the methods are run, which makes up the Java program flow.

We will arrange the method calls of the above line Cheng according to the running flow. There will be graphs like the following:


Based on the time series, we are able to line up the method calls. Each method invocation can be viewed as a node in the Java run stream. This node is referred to as the join point in the AOP terminology, that is, connection points . The process of running a Java program is a process in which several connection points are connected sequentially.

In our normal object-oriented thinking, we consider how to implement our business logic in terms of time series through method invocation. So. What is AOP (that is, tangent-oriented programming)?

Typically object-oriented programs, the code is expanded vertically according to the time series. And they all have a commonality: that is, the method call is expanded as a basic operating unit.

When a method call is treated as a connection point, a program that is strung by a connection point runs the process of running the program.

AOP (Aspect oriented Programming) considers the entire program from a different perspective. AOP programmed each method invocation, the connection point, as a programmatic entry for the method invocation. From a logical point of view, it is equivalent to a horizontal cut in a previously longitudinal program that runs according to the timeline.

Equivalent to dividing the previous program horizontally into a number of faces. That is aspect. Each polygon is called a slice.


So, according to my understanding, AOP is essentially a programming idea for method invocation.

since AOP is programmed for facets. So. Which facets do you need to choose (that is, connection points joint point) as your programming object?

because facets are essentially each method call. The process of selecting a slice is actually the process of selecting a method.

Then, the selected facet (Aspect) is referred to as the pointcut (Point Cut) in the AOP terminology. The pointcut is actually the process of picking a connection point of interest from all the connection points (join point).

The spring AOP Framework represents the Pointcut (point Cut) through a method-matching expression, and the specific expression syntax is not the focus of this article, so readers should refer to the documentation for the spring counterparts themselves.

Since AOP is programming for method calls (connection points), now you have selected the link---pointcut (point Cut) that interests you. So. What type of programming can AOP do with it? What can AOP do?

Before we get into this, we need to know a very important question: since AOP is programming for method calls, how does AOP capture method calls? To figure this out, you have to understand the proxy pattern in design mode. Let's take a look at what the Java program running flow is like when the proxy mode is introduced.

3. Introduction of the agent-mode Java program run Stream (mechanism of AOP implementation)

If we were in our Java code. Have created proxy objects for instance objects through proxy mode, access to these instance objects must pass through the proxy. So. Adding a proxy object to the Java program running stream can become slightly more complex.
Let's look at the addition of the proxy object after the Java program runs the stream:



It can be seen that the only way to invoke an instance object is to pass the corresponding proxy object of the instance object, that is, the control of the run is given to the proxy object first.

About proxy mode
Proxy mode is a frequently used and more important design pattern in Java code.

The proxy mode provides some additional functionality for some objects in addition to their own functionality. The approximate effect is for example with what is seen:

For specific introduction and analysis of Agent mode, please refer to my other blog post:
The Java dynamic Agent mechanism is explained in detail (JDK and Cglib. JAVASSIST,ASM)


Added a Java program run stream for proxy mode. So that all method calls are passed through the proxy object. For the spring AOP Framework, it is responsible for controlling the proxy objects inside the whole container. When we call an instance object, regardless of a non-final public method. The entire spring framework will be known.

At this point the SPRINGAOP framework plays a role of God in some way: It knows what you are doing within this framework, and your non-final public method calls to each instance object can be perceived by the framework!


Now that the Spring Agent layer is able to perceive every method call you make to an instance object, spring has the opportunity to insert spring's own business code into the proxy process.



4. How Spring AOP Works

As mentioned earlier, AOP programming first chooses the connection point to which it is interested----namely the pointcut (Point cut), then. What kind of programming can AOP do with pointcuts? We will first refine one of the connection points in the proxy mode. You will see, for example, the following procedure:


In order to reduce our understanding of spring's AOP, I have simplified the role of agent in this area, which is easy for everyone to understand.

( Note: The real spring AOP proxy role plays only a lot more complex than this.) Here is just a simplification, easy to understand, please do not preconceived ) proxy role of agent mode at least consider three phases:

1. What do I need to do before invoking the method of the real object ?

2. What do I need to do in the process of invoking a method of a real object, assuming an exception is thrown ?

3. after calling the method of the real object. What do you need to do to return the results?

AOP is programmed for this method invocation. is to insert your own business code for these three phases.


now if the current Realsubject class of this role is org.luanlouis.springlearning.aop.FooService , the corresponding method signature for the current connection point is: public void foo (). Then the three stages of the above proxy objects will have the following processing logic:

1. before invoking the method of the real object ,

proxy tells Spring AOP: "I'm going to call the public void foo () of Class Org.luanlouis.springlearning.aop.FooService , Before the call. Do you have any suggestions to deal with? ";

Spring AOP is then signed with the class name and method provided by proxy, and then attempts to match the information to see if it is within the pointcut of interest. Assuming that within the pointcut of interest, Spring AOP returns a methodbeforeadvice processing recommendation that tells the proxy what to do.

2. What do I need to do in the process of invoking a method of a real object, assuming an exception is thrown ?

proxy tells Spring AOP: "I call the public void foo () of class Org.luanlouis.springlearning.aop.FooService The procedure throws an exception, what do you have to deal with the suggestion? "

Spring AOP is based on the type and method signatures provided by proxy. identified in its interest in the pointcut, then return the corresponding processing recommendations Throwsadvice, tell the proxy this period should take action.


3. after invoking the method of the real object, the result is returned . What do I need to do?

proxy tells Spring AOP: " I called the class Org.luanlouis.springlearning.aop.FooService public void foo () ended and returned the results what do you propose to do now? ";

Spring AOP determines the pointcut within which it is interested, based on the type name and method signature provided by the proxy. Then return to the Afterreturingadivce processing proposal, Proxy gets this processing advice, and then runs the recommendation.


The above is a clear indication of what spring AOP should do: the corresponding processing recommendations are given at specific time stages of the specific class-specific methods that the proxy provides.

To complete the work. Spring AOP should implement:

1. Determine what kind of method you are interested in? The-----is to determine the point cut of the AOP, which can be done through the pointcut (point cut) expression.

2. How does the corresponding class of methods run at specific times to give advice on what to deal with? ------This requires spring AOP to provide the appropriate advice, which is what we often call advice.



End The basic working mechanism of AOP has been introduced, and I stress again that I have simply split the different operating periods of the proxy method into three in order to facilitate understanding of the working mechanism of AOP, and the actual implementation of the AOP proxy is much more complicated than this one.

Details of how the proxy is implemented, I will introduce another. If you are interested, please pay attention to my blog post.

Spring Design Idea Spring AOP implementation principle


Author's words
The design principle of spring AOP is only my personal opinion and opinion, if there are any questions and errors, please kindly point out, please enlighten us and make progress together.

The basic principles of AOP design of spring design thought

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.