AOP technology in Spring

AOP (aspect oriented programming) aspect oriented programming
The unified maintenance of program functions through precompile or runtime dynamic agent can be understood as extending functions without modifying the source code.

Execution flow of Java program

The process of program running is the process of method calling. We arrange the method calls in a string according to the order of method execution, which constitutes the Java program flow.
Arrange the method calls in the above thread stack according to the execution flow, as shown in the following figure

Based on time series, we can line up method calls. Each method call can be regarded as a node in the Java execution flow. In AOP terms, this node is called a Join Point, that is, a connection point. The running process of a java program is a process in which several connection points are connected and executed in turn.
Usually, the code of object-oriented programs is expanded vertically according to the time series, and they all have one common feature: that is, they are expanded with method calls as the basic execution unit. If the method call is regarded as a connection point, the program execution flow connected by the connection points is the execution process of the whole program.
AOP(Aspect Oriented Programming) considers the whole program from another perspective. AOP takes each method call, that is, the connection point, as the programming entry to program the method call. From the perspective of execution logic, it is equivalent to the horizontal entry of the previous vertical program executed according to the timeline. It is equivalent to cutting the previous program horizontally into several faces, i.e. Aspect. Each face is called cut face.
Therefore, according to my understanding, AOP is essentially a programming idea for method invocation.

AOP is programmed for facets. What facets (i.e. joint points) do you need to select as your programming objects?
Because facets are essentially every method call, the process of selecting facets is actually the process of selecting methods. Then, the selected aspect is called a point cut in AOP terminology. The point cut is actually the process of selecting the connection points of interest from all join points.
Third party

Since AOP is programming for method calls (connection points), and now you have selected the link point you are interested in - Point Cut, what kind of programming can AOP do for it? What can AOP do?
Before understanding this, we need to know a very important question: since * * AOP is programming method calls, how does AOP capture method calls** To figure out this problem, let's first understand what the execution flow of Java programs with proxy mode looks like.

Java program execution flow using proxy mode

We assume that in our java code, proxy objects are created for instance objects through proxy mode, and access to these instance objects must be through proxy. Then, the execution flow of Java programs with proxy objects will become a little more complex.
Let's take a look at the schematic diagram of the Java program execution flow after adding the proxy object:

As can be seen from the above figure, whenever you want to call the method of an instance object, you will pass through the proxy object corresponding to the instance object, that is, the execution control is handed over to the proxy object first.
Proxy pattern is an important design pattern often used in Java code. The agent mode can provide some additional functions for some objects in addition to their own functions, as shown in the following figure:

The Java program execution flow with proxy mode makes all method calls pass 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 non final public method of an instance object, the whole Spring framework will know.
At this time, the spring AOP framework plays a role of God to some extent: it knows any operation you do in this framework, and your non final public method calls to each instance object can be detected by the framework!

Since the Spring proxy layer can detect every method call you make to the instance object, Spring has the opportunity to insert Spring's own business code in the proxy process.

How Spring AOP works

It has been introduced that AOP programming should first select the connection point it is interested in, that is, the point cut. Then, what kind of programming can AOP do for the point cut? Let's refine a connection point in the proxy mode, and you will see the process shown in the following diagram:

In order to reduce the difficulty of understanding the AOP of Spring, I have simplified the functions of the proxy role here for your understanding. (Note: the proxy role play of the real Spring AOP can only be much more complex than this. It is only simplified here for your understanding. Please don't be preconceived.)
At least three stages should be considered for the agent role of the agent mode:
1. What should be done before calling the method of the real object?
2. What needs to be done if an exception is thrown during calling the method of the real object?
3. After calling the method of the real object, the result is returned. What should I do?

According to the type name and method signature provided by the proxy, Spring AOP determines that it is within the pointcut it is interested in, and returns the afterreturningadvce processing suggestion. The proxy obtains the processing suggestion and then executes the suggestion;

The above schematic diagram has clearly indicated what Spring AOP should do: give corresponding processing suggestions according to the specific period and stage of execution of specific methods of specific classes provided by proxy. To do this, Spring AOP should implement:
1. Determine what kind of methods are you interested in----- That is, determine the Point Cut of AOP, which can be completed through the Point Cut expression;
2. What processing suggestions are given for the specific execution period of the corresponding class method------ This requires Spring AOP to provide corresponding suggestions, that is, what we often call Advice.

AOP related terms

Join points: join points refer to those points that can be intercepted. In spring, it refers to methods. Spring supports the enhancement of method type join points. These methods are called join points.
Pointcut: pointcut refers to the definition of intercepting those connection points. There are right methods in the class that can be enhanced. The actually enhanced methods are called pointcuts
Advice: the value of enhancement is that the enhancement is what needs to be done after intercepting the connection point.
There are five types of enhancement: pre enhancement, post enhancement, exception enhancement, final enhancement and surround enhancement
Pre enhancement: executed before the connection point. Pre enhancement does not affect the execution of the connection point
Post enhancement: executed after the normal execution of the connection point
Exception enhancement: execute after the join point throws an exception
Final enhancement: after the connection point is executed, it will be executed regardless of the success or failure of the connection point
Surround enhancement: surround enhancement is before and after the connection point

Aspect: it is the combination of pointcut and enhancement, and the process of applying enhancement to pointcut

  • Introduction: introduction is a special notice. Without modifying the code, introduction can dynamically add some methods or fields to the class at run time
  • Target object: the target object of the proxy (the class to be enhanced)
  • Weaving: Yes, enhance the process of applying to the target and apply advice to the target
  • Proxy: after a class is enhanced by AOP weaving, a resulting proxy class is generated

Use of AOP

Integration and AspectJ framework in spring
AspectJ itself is a separate AOP framework, which is implemented based on Java, not a part of spring, and implements AOP operations together with spring
AOP can be implemented in two forms:
Implementation based on XML configuration form
Annotation based implementation

Introduce dependency
In addition to AOP dependencies, you also need to reference the basic core dependencies

 * intermediary
public class Broker {
public void  service1(){
        System.out.println("Look at the house");
    public void  service2(){
        System.out.println("Talk about price");
    public void  service3(){
        System.out.println("Give me the key");

Implementation of AOP based on XML configuration

Introducing AOP constraints into XML

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

Introduction to execution function

In the notification, the pointcut is defined through the value attribute, and the pointcut method can be defined through the execution function
1. Entry point: practical enhancement method
2. Common expression execution (< access modifier >? < return type > < method name > (< parameter >) < exception >)
(1) execution(* is a method in the table class
(2) execution(* com.tulun.bean.Book. (...)) table class all methods of a class in a package
(3) execution(. (...)) indicates all

Example: - match the execution of public methods of all classes (public. (...))
-Match the execution(* com.tulun.bean. * (...)) of all class methods under the specified package (excluding sub packages)

  • execution(* com.tulun.bean... * (...)) (including all classes under package and sub package)
  • -Match the execution of all methods of the specified class (* com. Tulun. Bean. Book. * (...))
  • -Match the execution of all class methods that implement a specific interface (* com. Tulun. Bean. Book +. * (...))
  • -Match all methods starting with com execution(* com * (...))

xml configuration:

 <!--Give the class to container management-->
    <bean id="landlord" class="com.tulun.Spring.AOP.Landlord"/>
    <bean id="broker" class="com.tulun.Spring.AOP.Broker"/>
<!--to configure AOP operation-->
    <aop:config >
        aop:pointcut label
        Configure pointcuts
        The join points to be enhanced are called pointcuts
        id Attribute: get name
        expression: Pointcut expression
        execution expression
        <aop:pointcut id="pointcut1" expression="execution(* com.tulun.Spring.AOP.Landlord.service(..))"/>
        aop:aspect label
        Configure section
        The process of applying enhancements to pointcuts
        ref Properties: specifying enhancements
         id Attribute: get name
         order Attributes: sorting multiple enhancements
        <aop:aspect  ref="broker">
            <!--Configure enhancement type:Pre enhancement-->
            <aop:before method="service1" pointcut-ref="pointcut1"/>

Enhancement type:

Test use:

        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("springcontext3.xml");
        Landlord landlord = (Landlord)applicationContext.getBean("landlord");

Execution results:

Various types of enhancements are as follows:

<!--Configure enhancement type:Pre enhancement( aop:before)-->
            <aop:before method="service1" pointcut-ref="pointcut1"/>
            <!--Post enhancement( aop:after )-->
            <aop:after method="service2" pointcut-ref="pointcut1"/>
            <!--Final enhancement( aop:after-returning )-->
            <aop:after-returning method="service3" pointcut-ref="pointcut1"/>
            <!--Abnormal enhancement( aop:after-throwing)-->
            <aop:after-throwing method="service4" pointcut-ref="pointcut1"/>
            <!--Surround enhancement-->
            <aop:around method="service5" pointcut-ref="pointcut1"/>

Implementation of AOP operation based on annotation

Introducing AOP operations into xml configuration files

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    <!--Enable annotation scanning-->
    <context:component-scan base-package="com.tulun.Spring.AOP"/>
    <!--open AOP operation-->

Add annotation on enhanced class

 * intermediary
//Open AOP operation for current class
public class Broker {
//Pre enhanced annotation, @ Before
    @Before(value = "execution(* com.tulun.Spring.AOP.Landlord.service(..))")
    public void  service1(){
        System.out.println("Look at the house");

@The Aspect annotation is added to the class to indicate that the current class is an enhanced class
@Before annotation is added to the method to indicate pre enhancement

@Before(value = "execution(* com.tulun.Spring.AOP.Landlord.service(...))")

About enhanced notes:

//Pre enhanced annotation, @ Before
    @Before(value = "execution(* com.tulun.Spring.AOP.Landlord.service(..))")
    //Post enhancement
    @After(value = "execution(* com.tulun.Spring.AOP.Landlord.service(..))")
//Final enhancement
    @AfterReturning(value = "execution(* com.tulun.Spring.AOP.Landlord.service(..))") 
    @AfterThrowing(value = "execution(* com.tulun.Spring.AOP.Landlord.service(..))") //Abnormal enhancement
    @Around(value = "execution(* com.tulun.Spring.AOP.Landlord.service(..))")//Surround enhancement

Tags: Spring Back-end AOP

Posted on Thu, 11 Nov 2021 17:04:58 -0500 by hussain