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. Features that Java programs run in the JVM
2. Java program execution Flow "Understanding the concepts of AOP, Connection points (join point), Pointcut (Point cut)"
3. Introduction of the proxy mode Java program execution flow (mechanism of AOP implementation)
4. How Spring AOP Works


1. Features that Java programs run in the JVM

When we write a main () method in a class Foo and then execute Java foo, your Java program's journey opens, as follows:

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

So what did the JVM do for you during this execution?

when you execute Java Foo , the JVM creates a main thread, the main thread, which takes the main () method above as a portal and starts executing your code. each thread maintains its own stack (stack) in memory, documenting the process of executing the entire program. 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, in memory corresponds to a stack frame in the stack and out of the stack.

about virtual machine line stacks (JVM Stack)
The model of the virtual machine line stacks (JVM thread Stack) is not the focus of this article, so it is not expanded here and the reader can view one of my other posts, which is described in great detail. java Virtual machine schematic diagram 3, JVM runtime data area]

At a particular point in time, a stack within a main thread renders the case as shown:


From a line stacks point of view, we can see that the basic unit of the JVM handling Java programs is 方法调用 . In fact, the instruction of the most basic unit that the JVM executes (that is, atomic operations) is the machine bytecode of assembly-language nature. The basic Implementation unit of Java program is viewed from a more macroscopic angle. 方法调用

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

Imagine how you can get the contents of a method call to the JVM line stacks? I believe that all Java programmer know the answer. Java programmer can see it almost every day------when our code throws an exception and is not caught or the error occurs when it runs , we get a very annoying log message , as follows:




of course, in addition to the code throws an exception, we can still be aware of other ways contents of the JVM line Cheng . You can use 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。 For exampleI executed it somewhere in the code. Thread.dumpstack () method, the following results are output:



2. Java Program execution Flow "Understanding the concepts of AOP, Connection points (join point), Pointcut (Point cut)"
If you consider Java program execution from the perspective of virtual machine line stacks, then 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 executed, which makes up the Java program flow.

We will arrange the method calls of the above line Cheng according to the execution flow, there will be similar graphs as follows:


Based on the time series, we can line up the method call. Each method invocation can be viewed as a node in the Java execution 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 executed 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)?

Usually 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 the basic execution unit. When a method invocation is treated as a connection point, the program execution flow that is strung by the connection point is the process of executing the whole program.

AOP (Aspect oriented Programming) considers the entire program from another perspective, and AOP takes each method invocation, the connection point, as a programmatic entry, programmed for the method invocation. From the logical point of execution, it is equivalent to a horizontal cut in a previously vertical procedure executed in accordance with the timeline. The equivalent of cutting the previous program horizontally into several faces, namely aspect. Each face is called a slice.
So, as I understand it, AOP is essentially a programming idea for method invocations.

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

because facets are essentially every 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. A pointcut is actually the process of picking a connection point of interest from all connection points (join point).

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

Since AOP is programming for method calls (connection points), and now you have selected the link---pointcut (point Cut) that interests you, 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 the Java program execution flow that introduced the proxy pattern.

3. Introduction of the proxy mode Java program execution flow (mechanism of AOP implementation)

We assume that in our Java code, we have created proxy objects for instance objects through proxy mode, and access to these instance objects must pass through proxies, so the Java program execution flow that joins the proxy object becomes slightly more complex.
Let's take a look at the addition of the proxy object, the Java program executes the flow:



As can be seen, whenever you want to invoke a method of an instance object, it goes through the proxy object corresponding to the instance object, that is, the execution of control 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 can provide some additional functionality for some objects in addition to their own functionality, as shown in the following:

For a detailed introduction and analysis of the proxy model, please refer to my other blog post:
A detailed description of the Java Dynamic Agent mechanism (JDK and Cglib,javassist,asm)


The Java program execution flow is added to the 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 any of the non-final public methods of an instance object, the entire spring framework will know.

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 detected by the framework!


Now that the spring agent layer can 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

The previous introduction to AOP programming is to select the connection point to which it is interested----the point cut, so what programming does AOP do with pointcuts? We will first refine a connection point in the proxy mode, and you will see the following procedure:


In order to reduce our understanding of spring 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 play can only be more complicated than this, here is only simplified, easy to understand, please do not preconceived ) proxy role of the 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 if I throw an exception during the method of invoking a real object ?

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

AOP's programming of this method invocation is to insert its own business code for these three phases.


Now let's assume that the current Realsubject class for this role is Org.luanlouis.springlearning.aop.FooService , and the current method signature for this connection point is: public void foo (). Then the three phases 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 , Do you have any suggestions to deal with before calling? ";

Spring AOP is then signed according to the class name and method provided by proxy, and then attempts to match it in the pointcut of interest, and if within the pointcut of interest, spring AOP returns the Methodbeforeadvice processing recommendations, Tell the proxy what should be done;

2. What do I need to do if I throw an exception during the method of invoking a real object ?

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, based on the type and method signature provided by the proxy, determines the action that should be taken during this period by returning the corresponding processing suggestion Throwsadvice in the pointcut to which it is interested.

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 deal with now? ";

Spring AOP, based on the type name and method signature provided by the proxy, determines that within its point of interest, the Afterreturingadivce processing suggestion is returned, and the proxy obtains the processing suggestion, then executes the recommendation;


The above is a clear indication of what spring AOP should do: give appropriate processing advice based on the specific phase of the specific method that the proxy provides for a particular class of execution. To complete this work, Spring AOP should implement:

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

2. What are the handling recommendations for the implementation of the method of the corresponding class in a given period? ------This requires spring AOP to provide the appropriate advice, which we often call advice.



So far, the basic work mechanism of AOP has been introduced, I again emphasize that the morning I will proxy method of the different execution period of the simple split into three, is to facilitate understanding of the AOP work mechanism, the actual implementation of AOP proxy more complex than this. Specific proxy is how to achieve, I will introduce another, interested in the words, please pay attention to my follow-up blog post.

Spring Design Idea Spring AOP implementation principle


Author's words
This article about Spring AOP design principle is only my personal views and opinions, if there are any questions and errors, please do not hesitate to 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.