preface

Only a bald head can be strong

The last article has explained the knowledge of Spring IOC! This article is mainly to explain Spring AOP module ~

Spring [AOP module] is as simple as that. It is a great honor to be recommended by Open Source China

  • If you don’t have an AOP foundation, I suggest you take a look at the article above
  • If there is no agency mode basis, it is suggested to have a look: explain to your girlfriend what is the agency mode of this article
  • If you have seen this article, rest assured to eat it!

This article will supplement and strengthen some of the more important knowledge points, and will organize the above two books on AOP knowledge points and draw a mind map to fully understand the knowledge points of Spring AOP!

So let’s get started. If there are any mistakes, please forgive them and correct them in the comments section!

A comprehensive understanding of Spring AOP

Combined with “Spring actual combat (4th edition)” and “proficient in Spring4.x enterprise application development actual combat” two books of AOP chapters will be organized up ~

1.1 summary of AOP

AOP is called aspect oriented programming, so what do we understand aspect oriented programming?

We can start by looking at this code:

When we learn Java object orientation, what if the code is repeated? It can be broken down into the following steps:

  • 1: extraction into methods
  • 2: Extract classes

The method of extraction into classes is called vertical extraction

  • Vertical extraction is realized by inheritance

However, our current approach does not work: even if we extract the class, we still have duplicate code because the logic (start, end, commit transaction) is attached to the method logic of our business class!

Now vertical extraction is no longer the way, AOP concept: is scattered in various business logic code of the same code through the way of horizontal cutting extraction into an independent module!

The diagram above is also clear, it is easy to crosscut the repetitive logic code (we can simply think of it as encapsulating a class), but we need to merge the logic code we crosscut into the business logic to perform the same function as before! This is the first problem AOP solves!

1.2 Spring AOP principle

The logic code we crosscut is merged into the business logic to perform the same functionality as before (before extraction)

We could have done this using proxies before we learned Spring AOP.

  • If I wrote to my girlfriend to explain what is the agency model of this article, it is not difficult to understand the above I said that sentence
  • What can an agent do? Proxies can help us enhance the behavior of objects! Using dynamic proxies is essentially a matter of intercepting object methods at call-time and modifying and enhancing them!

The underlying principle of Spring AOP is dynamic proxy!

Source “master spring4.x enterprise application development combat” a paragraph:

Implemented using pure Java, Spring AOP does not require a special compilation process or a special class loader, and it proxies enhanced code into target classes at run time. Spring AOP, IoC, and AspectJ can be seamlessly integrated in Spring.

The fourth edition of Spring Training

Spring AOP is built on dynamic proxies, so Spring’s support for AOP is limited to method interception.

Dynamic proxies come in two ways in Java:

  • JDK dynamic proxy
  • CGLib dynamic proxy

JDK dynamic proxies need to implement some interface, and our classes may not all have interfaces, so the CGLib proxy has ~~

  • The CGLib proxy generates dynamic proxy objects that are subclasses of the target class
  • Spring AOP defaults to using JDK dynamic proxies, or CGLib proxies if the proxy class has no interface.

Which JDK proxy or CGLib proxy should we use? In “Mastering spring4.x Enterprise Application Development combat” gave suggestions:

  • If it is a singleton, it is best to use the CGLib proxy. If it is a multi-instance, it is best to use the JDK proxy

The reason:

  • The JDK performs better when creating proxy objects than CGLib proxies, while generating proxy objects performs worse than CGLib proxies.
  • For a singleton agent, CGLib is recommended

This should give you an idea of what Spring AOP is: horizontal extraction of repetitive code with the same logic, weaving it into target object methods using dynamic proxy techniques to achieve the same functionality as before.

  • In this way, we write business with business code in mind, not business irrelevant code

1.3AOP implementer

AOP in addition to Spring AOP implementation, there are famous AOP implementor: AspectJ, but also may not have heard of the implementor: JBoss AOP~~

Let’s expand on AspectJ’s knowledge:

AspectJ is a language-level IMPLEMENTATION of AOP that extends the Java language, defines AOP syntax, and provides cross-cutting code weaving at compile-time, so it has a compiler dedicated to generating Class files that comply with the Java bytecode specification.

Spring, on the other hand, borrows many of AspectJ’s very useful practices and incorporates AspectJ’s AOP capabilities. But Spring AOP is essentially a dynamic proxy at the bottom, so Spring AOP does not require a dedicated editor

1.4 AOP terminology

Well, there are several terms used in AOP. Both books explain these terms, and I will try to make them clear:

Join point:

  • Where it can be intercepted: Spring AOP is based on dynamic proxies, so method intercepts. Each member method can be called a join point ~

Point of contact (Poincut) :

  • Specifically positioned join points: As mentioned above, each method can be called a join point, and when we specifically locate a method, it becomes a pointcut.

Enhancements/Advice:

  • Represents a segment added to the pointcutLogic codeAnd locate the connection pointAzimuth information.
    • It simply defines what it does, where it does it
    • Spring AOP provides five Advice types for us: front, back, return, exception, and surround for us to use!

Weave (has) :

  • willEnhancement/notificationProcedures added to specific join points of the target class.

Introduction/Introduction

  • Introduce/introduceAllow us toAdd a new method or attribute to an existing class. It is a kind ofspecialThe enhancement of!

Section (Aspect) :

  • The cut surface consists of the cut points andEnhancement/notificationComposition, which includes both the definition of crosscutting logic and the definition of join points.

The summary given in Spring Field (4th edition) is as follows:

Notification/enhancement includes crosscutting behavior that needs to be used for multiple application objects; Join points are all points during program execution where advice can be applied; The pointcut defines where the notification/enhancement is applied. The key is that pointcuts define which join points are notified/enhanced.

In summary:

  • These terms may not translate well, but they don’t have that much impact on how we normally use AOP.

1.5Spring’s support for AOP

Spring provides three types of AOP support:

  • Proxy-based classic SpringAOP
    • You need to implement the interface and manually create the proxy
  • Pure POJO section
    • Use XML configuration, AOP namespace
  • @AspectJAnnotation-driven facets
    • This is the simplest and most convenient way to use annotations!

Proxy-based classic SpringAOP

This part of the configuration is more troublesome, it is also very troublesome to use, here I will mainly sort out the content of the book, we have a look to understand it, we actually use Spring AOP basically do not need this way!

First, let’s look at the inheritance diagram for the enhanced interface:

There are five types of enhancements:

Spring provides six pointcut types:

Section types are mainly divided into three types:

  • General aspects
  • Cutting plane
  • Introduce/introduce the cut

General section, point section, introduction/introduction section introduction:

For pointcuts we usually use them directly. Let’s see how introduction/introduction cuts work:

  • Introduction/Introduction facets are introduction/introduction enhanced wrappers that make it easier to add implementations of any interface to existing objects by introducing/introduction facets!

Inheritance diagram:

The introduction/introduction aspect has two implementation classes:

  • DefaultIntroductionAdvisor: common implementation class
  • DeclareParentsAdvisor: An introduction/introduction aspect for implementing AspectJ’s DeclareParent annotation representation

In fact, we tend to use AOP internally in Spring to create proxies for us using BeanPostProcessor.

The creators of these agents can be divided into three categories:

  • Automatic proxy creator based on Bean configuration name rules: BeanNameAutoProxyCreator
  • Based on Advisor matching mechanism of automatic proxy creator: it will scan all the Advisor, the container for DefaultAdvisorAutoProxyCreator implementation class
  • Based on AspectJ annotations in the Bean label automatic proxy creator: AnnotationAwareAspectJAutoProxyCreator

Corresponding class inheritance diagram:

So much for proxy-based classic SpringAOP. Actually, I am reluctant to write about it because it is almost no longer used and is not covered in Spring In Action 4.

  • But you can get a more complete understanding of Spring AOP’s various interfaces through this section

Embrace annotation – and name-based AOP programming

In the new version of Spring, AOP features are enhanced in several ways:

  • An AOP namespace is provided for AOP in the XML configuration file
  • Added support for the AspectJ pointcut expression language
  • AspectJ can be seamlessly integrated

So what do we learn to play AOP with @AspectJ? In fact, this is the content above, learn how to set pointcuts, create cuts, what enhanced content is…

Specific pointcut expression use or go to: Spring【AOP module 】 so simple look ~~

Corresponding enhanced notes:

3.1 Introduce new methods to beans using the introduction/import implementation

In fact, front ah, post ah these are very easy to understand, the whole article read down only this introduction/introduction section is a bit interesting. So let’s play

Let’s see how it works. Now I have a server interface:


public interface Waiter {

    // Greet guests
    void greetTo(String clientName);

    / / service
    void serveTo(String clientName);
}

Copy the code

A young waiter realization class:


public class NaiveWaiter implements Waiter {
    public void greetTo(String clientName) {
        System.out.println("NaiveWaiter:greet to " + clientName + "...");
    }

    @NeedTest
    public void serveTo(String clientName) {
        System.out.println("NaiveWaiter:serving " + clientName + "..."); }}Copy the code

Now I want to do is: think this waiter can act as a salesman’s role, can sell things! Of course, I’m definitely not going to add a method to sell something to the Waiter interface because it’s temporary

So, I set up a salesperson interface:


public interface Seller {

  / / sell things
  int sell(String goods, String clientName);
}
Copy the code

A salesman implementation class:


public class SmartSeller implements Seller {

	/ / sell things
	public int sell(String goods,String clientName) {
		System.out.println("SmartSeller: sell "+goods +" to "+clientName+"...");
		return 100; }}Copy the code

At this point, our class diagram looks like this:

Now what I want to do is: use AOP’s introduction/introduction facets to enable our servers to sell things too!

Our lead-in/lead-in section looks like this:


@Aspect
public class EnableSellerAspect {
    
    @DeclareParents(value = "com.smart.NaiveWaiter".// Specify the specific implementation of the server
            defaultImpl = SmartSeller.class) // The specific implementation of the salesman
    public Seller seller; // The target interface to implement
    
}
Copy the code

What happens if I write this section class?

  • Slice technology fuses SmartSeller into NaiveWaiter, which implements the Seller interface !!!!

Isn’t it amazing? I think it’s amazing. Let’s test it out:

Our bean.xml file is simple:

<? The XML version = "1.0" encoding = "utf-8"? > <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd "> < aop: aspectj autoproxy / > < bean id =" waiter" class="com.smart.NaiveWaiter"/> <bean class="com.smart.aspectj.basic.EnableSellerAspect"/> </beans>Copy the code

Test it out:


public class Test {
    public static void main(String[] args) {


        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("com/smart/aspectj/basic/beans.xml");
        Waiter waiter = (Waiter) ctx.getBean("waiter");

        // Call the server's old method
        waiter.greetTo("Java3y");
        waiter.serveTo("Java3y");

        // The Waiter has implemented the Seller interface by introducing/introducing the section, so it can be cast
        Seller seller = (Seller) waiter;
        seller.sell("Water army"."Java3y"); }}Copy the code

The specific call process looks like this:

When an imported interface method is called, the proxy object delegates the call to some other object that implements the new interface. In effect, the implementation of a Bean is split into multiple classes

3.2 Declare facets in XML

We know that annotations are convenient, but to use Spring AOP in an annotated manner you must have the source code (because you will be adding annotations to the aspect class). Without the source code, we would have to use XML to declare facets

In fact, it is similar to annotation function:

Let’s finish it off with a straightforward example:

Let’s first test how the advisor works with traditional SpringAOP:

Implementation class:

XML configuration file:

.

It’s going to take too long to go through them one by one, so I’ll just do it in one shot:

Finally, there is a summary diagram of the section type, which is almost clear after reading:

The Spring ebook, if you are interested, you can browse through it. There are 142 pages

Third, summary

It seems that there are a lot of knowledge points about AOP. In fact, we just need to remember the core concepts of AOP.

Here is my brief summary of AOP:

  • The underlying layer of AOP is actually dynamic proxies, which are divided into JDK dynamic proxies and CGLib dynamic proxies. If the proxied object has no interface, the CGLIB proxy is used (you can also configure the CBLib proxy directly)
  • If it is a singleton, it is best to use the CGLib proxy because CGLib proxy objects run faster than JDK proxy objects
  • Since AOP is based on dynamic proxies, it can only intercept methods, and its level is method level
  • Whether you use Spring AOP in a classical, annotated, or XML configuration way, the principles are the same, but in a different form. Generally we use AOP the way we use annotations.
  • Annotation using Spring AOP to understand a few pointcut expressions, a few enhanced/notification annotations are done, is not a simple… The way you use XML is not that different from annotations, so you can get started very quickly.
  • The introduction/import section is also a bright spot where you can implement an interface to an object as a proxy, allowing you to use methods under excuses. This approach is non-invasive
  • The enhanced method can also accept the same parameters as the proxied method, bind the return value of the proxied method…

Finally, add our last IOC mind map to the AOP knowledge point

Open source project (6 K STAR) :Github.com/ZhongFuChen…

If you want to follow my updated articles and shared dry goods in real time, you can search Java3y on wechat.

The content of the PDF document is typed by hand. If you don’t understand anything, you can ask me directly (the official account has my contact information).