This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.


  • πŸ’¬ If the article is helpful to you, welcome to follow, like, bookmark (click three links) and subscribe.

πŸ’˜ 1. Preface

  • Hello, everyone, I am a little honesty, then happy learning time, last week because of junior partner to contribute, so wrote: “what is a program to an interface, the article is rather popular, and he has a friend advice is introduced about: aspect oriented programming knowledge, and there was this article, can’t, is so spoiled powder! (A billion points of narcissism…)

  • Because of my work and personal requirements, I have not updated the MySQL learning sequence series from 0 for a long time. However, please believe that this series will not be broken, xiao Cheng will continue to write with higher requirements and quality, I believe that we can bring more and better articles.

  • If the article is helpful to you, you can help to subscribe to the three key and column oh! If you meet some strange or novel topics in the interview, welcome private letter to contribute, thank you for reading (private letter I can contribute)!



πŸ’” 2. Column recommendation


JAVA and algorithmic spiritual technique column is still free to share, you can help subscribe!

JAVA Essentials

Practice of Algorithms


πŸ’• 3. First meeting – Faceted programming


In the previous article, we introduced interface oriented programming, and now we introduce aspect oriented programming. What is the connection between the two? Here we go slowly!

AOP(short for aspect-oriented Programming), which stands for Aspect Oriented Programming, is a Programming idea described in Spring’s official documentation: Aspect oriented programming (AOP) provides another way of thinking about program structure to complement and improve OOP, where objects are the key, while aspects are the key.

Aspects in AOP enable modularization (that is, uniform extraction, improved reuse) of concerns, such as transaction management across multiple types and objects, which are often referred to as crosscutting concerns in the AOP literature.



Text descriptions may seem abstract, but let’s use examples and pictures to visualize these concepts.

Example: taking a bath (disclaimer, the following steps are personal ideas, not on behalf of everyone, if you feel my idea is not rich enough, welcome to comment, send you hot search)

Steps (male) : Undress, sing, wash your face, wash your hair, wash your body, dry your body, put on your clothes

Procedure (female) : Undress, wash face, wash hair, care hair, wash body, dry body, skin care, dress

Found the problem: through the example above, we will find that both men and women, take off your clothes, wear clothes is bathing indispensable steps, and these two steps in the “shower” this business is not the core, it is just a concern, because take off clothes and wear clothes scenario is not just in the shower (what scenario yourself lenovo, such as: We need to take off clothes in hot weather and wear clothes in cold weather. Therefore, it is a more reasonable design to define clothes management as a module and call it where necessary, as shown in the following figure:



summary

Through an article we can know that the emergence of the object-oriented programming (OOP) allows developers to implement the business logic of the vertical, but the object oriented programming (OOP) is not suitable for used to define the transverse business logic relationship, this design will lead to a large number of duplicate code system, poor reusability, such as the most common log, and transaction capabilities, They may be horizontally distributed in different business hierarchies (object hierarchies), but have no direct relationship to specific core businesses. Such types of code are called cross cutting in programs. We should consider unified management of this type of code to improve reusability.

Aspect oriented programming (AOP) is to extract and encapsulate the common behaviors of these classes that have nothing to do with core business but affect many classes into a reusable module, so as to achieve the purpose of code reuse and module decoupling. This development idea is called aspect oriented programming.


πŸ’– the role of section-oriented programming


From the above examples and graphics, you have a preliminary understanding of aspect programming, so let’s take a look at what aspect programming can give us.

πŸ’ 4.1. Reduce the coupling degree between modules


System implementation “high cohesion, low coupling” has been the pursuit of our program developers. AOP technology divides the software system into two parts: core concerns and crosscutting concerns. The core functions of the business are the core concerns, and those irrelevant or little related to the business are crosscutting concerns.

Crosscutting concerns always act around the core concerns and have similar business meanings. Common concerns in system development, such as permission authentication, transaction management, and logging (for example, all input parameters of request interfaces need to be recorded in logs), are crosscutting concerns.

The appearance of AOP technology, the system’s core concern and crosscutting concern separation, avoid the non-core business coupling in the core business, reduce the coupling degree between modules, improve the readability, operability and maintainability of the system.

🌸 4.2 code reuse


AOP technology will have nothing to do with the core business or not related to the different business module common or needed logic extracted into new modules, in need of reintroduction, greatly reduce the system of repeated code. (Here’s a question for you to consider: why introduce AOP when you can reuse code by simply inheriting or extracting common classes?)


πŸ’— realization classification of section-oriented programming


The effect of aspect oriented programming (AOP) is to add some common logic irrelevant to the core business to some components of the system without modifying the source code. AOP framework is essentially to modify the source code of the target object and generate proxy objects with new functions. According to the timing of the modification of the source code of the target object, AOP frameworks can be divided into the following two broad categories:

🌹 5.1 static AOP implementation


Adopted the scheme of AOP framework will compile phase need to strengthen the program code, modified to generate static AOP proxy classes, namely that actually compiled class files is actually enhanced after the proxy class, because of the particularity of compile time, so in order to realize static AOP need to use a special to the compiler. A common static AOP framework is AspectJ

πŸ₯€ 5.2. Dynamic AOP implementation


AOP frameworks that use this approach generate proxy objects for target objects only at runtime (such as in-memory, using JDK dynamic proxy technology or CGlib dynamic bytecode technology). The most common framework for this approach is Spring AOP(which is the subject of this article).

🌺 5.3. Comparison of features between different AOP frameworks



πŸ’™ Terminology for faceted programming


From the above, we have a general impression of aspect programming, let’s start to understand the relevant knowledge about aspect programming.

To understand the essence of aspect programming, it is necessary to understand the terms of aspect programming, even if you do not know what the terms mean, how to recognize and use them. Let’s start with a picture that visually illustrates one of the connections between common AOP terms.



You may be confused after reading the above picture, but it doesn’t matter. Here is a detailed introduction to AOP related terminology, and then look at the diagram above again, I believe you will have a deeper understanding.

🌷 6.1 Related concepts


1, the increase of

It can be understood that a class can do something that it could not do before, such as: In the bathing example above, the bathing method does not include “undress” and “put on” functions, but by using AOP to make the “bathing method” have both functions, we can say that the “bathing method” has been enhanced (just look at Captain America, hit a pill can hammer out the earth….). .

Common enhancement methods: inheritance, decorator pattern, dynamic proxy (just a hint, can you guess which one this article uses to implement enhancement?)

2. Target Objects:

This is the object generated by the class we need to enhance, such as the object corresponding to the class that contains the “shower” method in the above example.

3. Proxy object:

With an AOP framework, a new object generated by enhancing the target object can have behaviors and properties that the target object does not have.


🌱 6.2 Advice


The specific functions and usage scenarios of the aspect, which defines what the specific functions of the aspect are and when they are used. In the bathing example above, the “specific function” of the section is :” undress and dress “, and “when used” is :” undress before bathing “and” dress after bathing “.


🌿 6.3 Notification type


In Spring, there are five types of notifications, depending on when they are used. Let’s take a look at each one.

  • Pre-notification (Befor) : Notification function that is invoked before the target method is called. As in the example above, the “undress” notification is executed before the “shower method” is called.

  • After notification: Notification that is invoked After the target method completes, even if an exception occurs during execution of the target method. In the example above, you spray in the shower, but continue to complete the “get dressed” notification after the shower.

  • After-returning: Notification is called After successful execution of the target method. In the example above, the toilet exploded in the shower and was directly sent to the hospital, so the notification function of “wear clothes” would not be invoked (too smelly….).

  • After-throwing: Notifying After the target method throws an exception. As the above example, in the shower, the toilet exploded again, but I prepared in advance how to do after the toilet exploded plan, once this anomaly occurs, I will call this notification function, can not go out naked.

  • Around advice: Advice surrounds the target method, and custom advice can be performed before and after the target method is called. As in the example above, the two functions of undressing before taking a shower and dressing after taking a shower can be done directly through the surround notification.


☘️ 6.4 Join Points


It represents a point during the execution of the business logic at which facet notifications can be inserted. In Spring, this point can be when a method is called, after a method is called, or when an exception is thrown. These points can be used by aspect code to plug into the normal flow of your application and add new behavior.

Spring AOP is based on dynamic proxies, so it only supports method join points, but other AOP frameworks like AspectJ can weave in notifications when properties are modified or when constructors are executed, achieving finer granularity of control interception.


πŸ€ 6.5 Pointcut


Advice defines the “what” and “when” aspects are used, and the “where” aspects are used. By configuring pointcuts, you can weave notifications into one or more join points. As in the example above, before and after the execution of the bathing method can be understood as the pointcut.

In practice, it is by specifying the class name, method name, regular expressions to match the specified point of tangency, even there are some AOP framework allows moving to create dynamic point of tangency, according to the runtime decisions (such as: method of parameter values) to determine whether to need to use the notification enhancement (these are some of the knowledge, expand temporarily does not involve) in this paper.

🌿 6.6. Aspect


A section is a collection of pointcuts and notifications that define what it is and when and where it is done. As in the example above, the before and after execution of the bathing method can be understood as pointcuts, and “undress” and “put on clothes” can be understood as notifications.


☘️ 6.7 Introduction


By allowing new attributes and methods to be added to a class, you essentially enhance the class (giving it functionality or attributes that it didn’t have before). This can be interpreted as applying the aspect to the target class to enable it to have new functions and properties without modifying the code of the class.


πŸ€ 6.8 Weaving


Weaving is the process of applying an aspect to a target object and creating a new proxy object. It is a dynamic process. The aspect is woven into the target object at the specified pointcut.

Compile time: The aspect is woven in when the target class is compiled. This approach requires a special compiler. AspectJ’s weaving compiler weaves facets in this way.

Class loading time: The aspect is woven when the target class is loaded into the JVM. This approach requires special classloaders that enhance the bytecode of the target class before it is introduced into the application. AspectJ 5’s load-time Weaving (LTW) supports weaving into sections in this way.

3. Runtime: The facets are woven in at some point during the application run. Typically, the AOP container dynamically creates a proxy object for the target object when weaving into the cut. Spring AOP is woven into the facets in this way.


πŸ’š the relationship between AOP, Spirng AOP and proxies


The previous introduction of more theoretical knowledge, you may be confused with some concepts, the following is a specific introduction of these concepts, to help you better examples of these concepts.

🍁 7.1. Agency


The most common example in life is second-hand dong. The real landlord will usually pay the salary to the second owner and then entrust the second owner to help deal with the rental and other matters. In this example, the second owner is the agent of the landlord, responsible for running errands for the landlord.


πŸ‚ 7.2 dynamic proxy


In the program run time, dynamic creation of the target object proxy object, and the target object method for functional enhancement of a technology, according to the implementation can be divided into: JDK dynamic proxy and CGlib dynamic proxy.


πŸƒ 7.3、Spring AOP


Through the introduction of the above we know that AOP is a programming idea, not a specific technology or framework, this idea extends out of the framework called AOP framework, Spring AOP is one of them, Spring AOP is built on dynamic proxy. It includes JDK dynamic proxies and CGlib dynamic proxies. Spring AOP uses JDK dynamic proxies to generate proxy objects for a class if it implements an interface, and CGlib proxy techniques to generate proxy objects if it implements an interface.


πŸš‰ 7.4. AOP types supported by Spring


  • Classic Proxy-based Spring AOP

  • Pure POJO aspect (Implementing Spring AOP with XML and POJO, with emphasis)

  • @AspectJ annotation-driven facets (annotation-based implementation of Spring AOP, with emphasis)

  • Injection AspectJ facets (available for Spring versions).

Proxy-based classic Spring AOP, implemented through ProxyFactory beans, can seem cumbersome and complex with the introduction of simple declarative AOP and annotation-based AOP, so this article will not cover the use of the fourth option, which requires some additional knowledge. It is not covered in this article.


🚊 7.5. Some features of the Spring AOP framework


1. Contrast the Spring AOP framework with the AspectJ framework

Spring AOP’s advice is written in Java, which makes it as quick to use as normal Java functionality, and provides both XML and annotations to give developers more options. AspectJ, on the other hand, was originally extended as the JAVA language, allowing for more power and fine-grained control, but requiring learning new tools and syntax.

2. How does Spring AOP implement enhanced target objects

The proxy object actually contains the aspect and the target object, and you can intercept the invocation of the notification method. When the caller makes the invocation, the aspect logic is executed and then the call is forwarded to the bean of the target object, which is enhanced because the proxy object is created at run time. So Spring AOP doesn’t require a special compiler to implement section weaving like AspectJ does, as shown in the following figure:



Spring AOP supports only method-level join points

Not all AOP frameworks are created equal, and different frameworks may have strengths and weaknesses in their join point models. For example, AspectJ provides field and constructor pointcuts in addition to method pointcuts. Because Spring AOP is based on dynamic proxies, it only supports method-level join points. However, method interception already meets most requirements. You need to use other AOP frameworks such as AspectJ.


πŸ’œ a pointcut indicator for Spring AOP support


Note: Although this article is about Spring AOP, there is actually a lot of collaboration between Spring and AspectJ projects, and Spring’s support for AOP borrows from the AspectJ project in many ways, such as pointcut indicators.

As mentioned above, pointcuts are the combination of advice and pointcuts, which define where advice should be applied. In Spring AOP, pointcuts are implemented using pointcut indicators to match specific join points.



Summary: There are a number of indicators listed above, but only the execution indicator actually performs the match. The rest of the indicators are only used to restrict the match, such as men’s room entry only, women’s room entry only, and the ladyboy can only stand outside!

Because there are many types of pointcut indicators, here are just a few examples of commonly used indicators. There will be a special article on how to use each indicator. Be sure to subscribe to the column below!

Warm reminder: the above indicator does not need to be memorized by rote, in the use of the time if you forget to query directly, we learn AOP is more important to understand this kind of programming ideas and use, and not to memorize some of the key words here, which is not only a waste of time and low efficiency.


πŸš‹ 8.1, Spring AOP cut point expression example analysis


The expressions written in the pointcut indicator to match join points are called pointcut expressions, and with pointcut expressions, we can match methods that need to be enhanced according to our needs. To give you a clearer understanding of the pointcut expression, as in the bathing example above, we have abstracted it into the following code, which various users have implemented:

package wash;
public interface Wash{
    void takeAWash(a);
}
Copy the code

Suppose we want to implement the “undress, undress” behavior whenever we call the “shower” method, then the tangent expression definition is as follows:



Thus, we can summarize a format syntax of the pointcut expression as follows:

Return value type package name. Class name. Method name (parameter)), where * indicates any type, and method parameter.. Represents an arbitrary parameter.

🚌 8.2, Spring AOP common indicator parsing


Commonly used annotations

1. @pointcut: Encapsulates the same Pointcut expression and provides a unified reference



@within: matches all methods held within the specified annotation type; Within is used to match method execution within the specified type;



Pointcut wildcard

  • * Wildcard: represents any number of characters, such as:


// Match the takeAWash method of the com.demo.IPerson class with any return value type and any argumentsexecution(* com.demo.IPerson.takeAWash(..) )Copy the code


  • . Wildcard: matches any parameter in any package or method in the system, for example:


// Match any name, any return value, any parameter methodexecution(* *(..) )// Matches all methods of all classes under com.demo and its subpackages
within(com.demo.*)
Copy the code


  • + wildcard: Represents any subclass of a given class


// Matches any subclass of the Demo interface
within(com.elvis.springaopinaction.Demo+)
Copy the code


πŸ’ Some problems in Spring AOP


πŸš– 9.1. What is the relationship between AOP and OOP


OOP(object-oriented programming) focuses on the abstract encapsulation of the attributes and behaviors of the problem entity in business processing, so as to achieve a clearer and efficient division of logical units and improve the comprehensibility and easy maintenance of the system.

AOP (aspect oriented programming) focus is the core focus of the system and the separation of crosscutting concerns and core concerns focus on core business processes, crosscutting concerns focus has nothing to do with the core business is the public behavior of core business references, will they separate extraction into a new module, and core business, reduce the coupling between modules, to improve the reusability of the code, It can be said that object-oriented programming (OOP) to complement and improve.

🚐 9.2 What is the difference between after-returning and post-returning


After: Indicates a notification function that is executed After the execution of the target method, even if an exception occurs during the execution of the target method.

Post-returning notification: The target method has completed post-returning notification. In the event of an exception, the notification logic will not be executed.





πŸš‘ 9.3. What is the order of execution of the five notifications


Order of execution when no exception is included:

Business Logic = “AfterReturning” = “AfterReturning” =

Order of execution when an exception is included in the execution of a business:

Around-before = Before = AfterThrowing = AfterThrowing = After = Around-after = Exception output caught in the around-after notification



πŸš’ 9.4. Why introduce AOP when you can enhance it through inheritance or decorator patterns


This question above has left a suspense, let us think, do you know if you guessed right?

In JAVA, the three most common ways to implement object enhancement are inheritance, decorator pattern, and dynamic proxy. Let’s take a concrete example to understand the differences between the three approaches.

Taking drinking milk tea as an example, we can add ingredients such as pearl, coconut and red bean to milk tea to get the taste we like. These ingredients change the taste of original milk tea. We can say that milk tea is “enhanced” with JAVA code as follows:

1. Enhanced inheritance mode

/** * milk tea base */
public class MilkTea {
    public void makeMilkTea(a){
        System.out.print("Original milk Tea"); }}/** * with pearl milk tea */

class PearlMilkTea extends MilkTea{

    @Override
    public void makeMilkTea(a){
        super.makeMilkTea();
        System.out.println("  + 加珍珠"); }}/** * add coconut grandma tea */

class CreamMilkTea extends MilkTea{

    @Override
    public void makeMilkTea(a){
        super.makeMilkTea();
        System.out.println("+ Coconut milk"); }}Copy the code

If another person wants to drink pearl Coconut grandma tea at this time, we need to create a PearlCreamMilkTea subclass (code as follows), and so on, we need to maintain each permutation and combination through a new class, which is prone to class explosion, so as to maintain, at this time, We can solve this problem with the decorator pattern:

// Pearl coconut grandma tea
class CreamMilkTea extends PearlMilkTea {

    @Override
    public void makeMilkTea(a){
        super.makeMilkTea();
        System.out.println("+ Coconut milk"); }}Copy the code


2, decorator way to enhance

/** * Abstract component: Defines an abstract interface to specify classes that prepare additional functionality */
public interface IMikeTea {
    void makeMilkTea(a);
}

/** * Concrete component: the class to be attached to implement the abstract component role interface */
public class MikeTeaImpl implements IMikeTea{
    @Override
    public void makeMilkTea(a) {
        System.out.print("Original milk Tea"); }}/** * Abstract decorator: Holds references to concrete component roles and defines interfaces that are consistent with abstract component roles */
public abstract class DecoratorMikeTea implements IMikeTea{

    private IMikeTea mikeTea;

    public DecoratorMikeTea(IMikeTea mikeTea) {
        this.mikeTea = mikeTea;
    }


    public void setIMikeTea(IMikeTea mikeTea){
        this.mikeTea = mikeTea;
    }

    @Override
    public void makeMilkTea(a){ mikeTea.makeMilkTea(); }}/** * Concrete decoration: Implements the role of abstract decorator, responsible for adding additional functions to concrete components. * /
public class ConcreteCreamMilkTea extends DecoratorMikeTea{

    public ConcreteCreamMilkTea(MikeTeaImpl mikeTea) {
        super(mikeTea);
    }

    @Override
    public void makeMilkTea(a){
        super.makeMilkTea();
        System.out.print("+ Coconut milk"); }}...Copy the code

The test code is as follows:

/** * Test decorator mode */
public class DecorarorMilkTeaTest {
    public static void main(String[] args) {
        MikeTeaImpl man = new MikeTeaImpl();
        ConcreteCreamMilkTea md1 = new ConcreteCreamMilkTea(man);
        ConcretePearlMilkTea md2 = new ConcretePearlMilkTea(man);

        // Pearl milk tea
        md1.makeMilkTea();
        System.out.println();
        // Coconut grandma tea
        md2.makeMilkTea();
        System.out.println();
        // Pearl coconut grandma teamd1.setIMikeTea(md2); md1.makeMilkTea(); }}Copy the code


By comparing the inheritance approach above, we can see that even if we add a permutation, we don’t need to maintain the corresponding code through a new subclass. We can add new responsibilities to the object dynamically by decorating the pattern (note: the above example shows only part of the code; all of the code has been uploaded to Spring-in-Action).

Inheritance, decorator pattern, AOP(dynamic proxy) summary

(1) Inheritance one of the three features in object-oriented programming, which allows us to subclass inherit properties or behavior specific to the parent class, thereby improving code reuse.

Advantages: Feature enhancement and code reuse

Disadvantages: JAVA is single inheritance, which increases the coupling between classes, leading to a fragile object architecture that can explode into subclasses that are difficult to maintain if the scene gets complicated.

(2), Decorator Pattern

It can dynamically extend the functions of an object, is more flexible than inheritance, and is essentially a combination of ideas. Inheritance is a behavior of subclasses that is determined at compile time, and can be extended dynamically at run time if the object is extended by composition.

Advantages: in line with the open and closed principle, with more flexibility than inheritance, can design different decoration classes and permutation of them, so as to meet the combination of different scenes.

Disadvantages: More complex and difficult to develop than using inheritance.

(3) AOP(dynamic proxy)

The non-core business is decoupled from the core business and dynamically woven in where necessary, which greatly improves the reusability and extensibility of the code.

(4) Differences between inheritance, decorator pattern, and AOP

  • When using inheritance enhancement: the enhanced object is fixed, and the enhanced content is fixed

  • When enhanced with decorator mode: Enhanced objects are toggable, enhanced content is fixed

  • When using section-oriented programming: Its enhancers and enhancements are switchable and more flexible than decorator, which is why we also introduced the AOP pattern with the inheritance and decorator pattern.


πŸ’ž 10


The following two ways to achieve the application of Spring AOP through annotations and XML! Because there is a lot of demo code involved, only part of the code and screenshots will be released in the example. All the code will be uploaded to Gitee. If you want to know about it, you can reach it through the Spring-in-Action express!

πŸ”΄ 10.1 use annotations to implement the use of Spring AOP


1. Add dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
    <version>2.37..RELEASE</version>
</dependency>
Copy the code


2. Abstract “bathing behavior” and implement it through concrete implementation classes



3. Add a section


4. Perform tests


🟠 10.2 use XML to implement the use of Spring AOP


1. Same as above, introduce corresponding dependencies (note: add the following code if the runtime tells you that the corresponding class is not found)



2. Add notifications and corresponding test entities



3. Add the XML configuration file



4. Test execution results



summary

Through the above examples, it is actually relatively easy to start using the corresponding AOP framework after understanding one of the programming ideas of AOP. The above example simply uses pre-notification and post-notification, and more notification applications have been delivered to Gitee.


πŸ’Ÿ 11. Write at the end


“Paper come zhongjue shallow, must know this to practice”, because AOP design of professional terms or more, to really master just read the article or not, must personally practice, we quickly act up, such as in practice, can private letter I!

Because of space limitation, aspect oriented programming knowledge involved too wide, this article is from a analysised the basic aspects of aop, and many of the details were not read, but any knowledge is a plus ca change, as long as the knowledge of “root”, corresponding to the knowledge of other development can be very good to understand.

After reading the article, if you want to have a deeper understanding of Spring AOP and even Spring, I recommend you to read the book “Spring In Action”. Personally, I have read part of it and feel very useful. If you want an electronic version, you can send me a private message.

The second wave of benefits is coming. In order to facilitate blog management, I have recently opened the CSDN annual VIP, which has some free download privileges. If any fans have urgent download needs, they can send me a private message! If articles help, don’t forget to subscribe to ღ(Β΄ Β· α΄— Β· ‘) than Heart!

Note: the code for all cases in the article has been uploaded to “Spring-in-Action”, need to be self-available, don’t forget to give a star oh.

Learning, communication, cooperation, please pay attention to [IT learning diary] public number, grow together!

🏳️🌈


Spring Official Documentation

Spring Practice – 4th edition

Faceted programming in Spring