— All brain maps are made by myself, do not abuse without permission –!! The overall focus is on Ioc and AOP source code analysis, while combining handwriting to achieve full “get it to fish”

Overview of Spring


1.1 introduction

It is a layered full-stack lightweight open source framework with Ioc and AOP as the kernel. The Spring Framework is designed to integrate many of the well-known third-party libraries and class libraries in the open source world

Official website usage:

1.2 the Spring ‘s History

  • 1997~2006: EJB1.0 -> EJB3.0
  • 2017.09:Rod Johnson’s team releases Spring5.0 General Release (GA)

1.3 Long-term Advantage

“Decouple, simplify development”

Dependencies between objects are handed over to the Spring container, avoiding hard-coded program coupling; Users no longer need to change the code for the underlying requirements and can focus on the upper-level business implementation.

“AOP Programming Support”

With its faceted programming capabilities, AOP can easily solve many of the problems that are difficult for OOP to implement.

Declarative Transaction Support

Transactional transactions are often tedious to manage, but declarations make them more efficient.

“Support for simple Tests”

You can do almost all of your testing in a non-container-dependent programming way, and testing is no longer an expensive operation, but something you can do on the fly

“Easy inheritance of various excellent frameworks”

Spring makes it easier to use frameworks and provides direct support for excellent frameworks (Struts, Hibernate, Hessian, Quartz, etc.)

“Making JavaEE apis easier to use”

Spring has a thin wrapper around JavaEE apis such as JDBC, JavaMail, remote calls, and so on, making them much easier to use

“The source code design is excellent, it’s a classic.”

Spring’s source code is well designed, well structured and uniquely designed, reflecting the master’s flexible use of Java design patterns and profound attainments in Java technology.

Its source code is undoubtedly an example of best practices in Java technology

1.4 Core Structure

1.5 Real-time query version and support

Check the recommended version on the official website

Get official recommended JDK support

Be sure to keep the JDK above 8+ when using Spring 5.x+

Second, core ideas

Icos and AOP were proposed before Spring, but they were theoretical then. Spring implements them theoretically

2.1 What is Ioc? What problem does Ico solve?

Inversion of Control

It’s a technical idea, not a technical implementation

  • Traditional development: A depends on B, so new A B object in A

  • Developed with an Ioc mind: the ‘new object ‘action is instantiated and managed by the Ioc container (the Spring framework); The programmer can ask the container which one he needs.

Analysis [control + inversion]

  • Control – the right to create (instantiate, manage) objects
  • Reverse — Give control to the external environment (Spring framework, Ioc container)

Solution: Decouple

2.2 Difference between Ioc and DI

They describe the same concept, but from different angles

  • The Ioc standing inObject Angle

    The instantiation and management of objects are transferred to the container.
  • DI stoodAngle of container

    When A depends on B, the container creates an instance of B and then injects it into A.

2.3 What is AOP? What problem does AOP solve?

Aspect Oriented Programming is a continuation of OOP

  • Three characteristics – encapsulation, inheritance, polymorphism

2.4 Why is it called ‘faceted’?

  • “Cut” from the vertical business flow into the function;
  • “Surface” usually cuts into the function, affecting more than one method, each affected method is cut into a point, multiple points constitute the surface.

Three, handwritten Ioc and AOP

Simulate the bank transfer project

Pull open source test code (annotate old records at each step)

The front page

The database

“Basic content plus meals”

A Review of the simple factory model


public interface INoodles {
    
    /** * describe the noodles */
    void desc(a);
}

public class LaMian implements INoodles {
    @Override
    public void desc(a) {
        System.out.println("A bowl of ramen from Lanzhou"); }}public class PaoMian implements INoodles {
    @Override
    public void desc(a) {
        System.out.println("A bowl of instant noodles from the supermarket."); }}public class DanDanMian implements INoodles {
    @Override
    public void desc(a) {
        System.out.println("A bowl of Dan Dan noodles from Sichuan."); }}public class SimpleNoodlesFactory {
    
    public static final int LM = 1;
    public static final int PM = 2;
    public static final int DDM = 1;
    
    public static INoodles createNoodles(int noodleType) {
        switch (noodleType) {
            case 1:
                return new LaMian();
            case 2:
                return new PaoMian();
            case 3:
                return new DanDanMian();
            default:
                return null; }}}Copy the code

test

public class Test {
    
    public static void main(String[] args) {
        SimpleNoodlesFactory.createNoodles(1).desc();
        SimpleNoodlesFactory.createNoodles(2).desc();
        SimpleNoodlesFactory.createNoodles(3).desc(); }}Copy the code

B Dom4j + xpath
Match the pattern instructions
nodename Selects all children of this node
/ From the root node
// Nodes in the document are selected from the current node selected by the match, regardless of their location
. Select the current node
. Selects the parent of the current node
@ Select properties

Rely on

<! --DMO4J-->
<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
    <scope>test</scope>
</dependency>
<! --xpath expression -->
<dependency>
    <groupId>jaxen</groupId>
    <artifactId>jaxen</artifactId>
    <version>1.1.6</version>
</dependency>
Copy the code

The test file


      
<books>
    <book num="1001" name="Thinking in JAVA">
        <version id="1.0" time="2017.09"/>
    </book>
    <book num="1002" name="Leaning Python"/>
    <book num="1003" name="C Primer Plus"/>
    <book num="1004" name="Sharp Jquery"/>
</books>
Copy the code

The test class

@Test
    public void test(a) throws DocumentException {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("books.xml");
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(resourceAsStream);
        Element root = document.getRootElement();
        // nodeName directly -- selects all children of the node
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
        List<Element> bookList = root.selectNodes("book");
        for (Element element : bookList) {
            Attribute attrib = (Attribute) element.selectNodes("@num").get(0);
            System.out.println( attrib.getValue() + "-" + element.attributeValue("name"));
        }
        // / -- select from the root node
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
        List<Element> firstNode = root.selectNodes("/bookStore");
        for (Element element : firstNode) {
            System.out.println("Root node:" + element.attributeValue("Sname"));
        }
        // // -- Select nodes in the document from the current node selected by match, regardless of their location
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
        List<Element> innerBooks = root.selectNodes("//book");
        for (Element element : innerBooks) {
            System.out.print(element.attributeValue("name") + "\t");
            / /.. -- Selects the parent node of the current node
            List<Element> fatherNodes = element.selectNodes("..");
            for (Element fatherNode : fatherNodes) {
                System.out.println("--> The parent node is:" + fatherNode.attributeValue("Sname")); }}//. -- Selects the current node
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
        List<Element> currentNodes = root.selectNodes(".");
        for (Element element : currentNodes) {
            System.out.println("Current node:" + element.attributeValue("Sname")); }}Copy the code

C Singleton mode
  • The hungry mode
public class HungrySingleton {
    
    // Privatize the constructor (a necessary step for the singleton)
    private HungrySingleton(a) {}
    // Set the self-instantiated object to a property, with static and final
    private static final HungrySingleton instance = new HungrySingleton();
    // The static method returns the instance
    public static HungrySingleton getInstance(a) {
        returninstance; }}Copy the code
  • Lazy mode
public class LazySingleton {
    
    // Privatize the constructor
    private LazySingleton(a) {}
    // Set the self-instantiated object to a property and decorate it with static
    private static LazySingleton instance;
    Static method returns the instance with the synchronized keyword.
    public static synchronized LazySingleton getInstance(a) {
        if(instance == null) {
            instance = new LazySingleton();
        }
        returninstance; }}Copy the code
D Annotation Basis

@ Target annotation

Specifies the range of objects that the Annotation modifies:

  • Fields are used to describe fields
  • PACKAGE is used for packages
  • TYPE is used for types (class, interface, enumeration, Annotation TYPE)
  • METHOD/CONSTRUCTOR is used for type members (methods, constructors, member variables, enumerated values)
  • PARAMETER is used for method parameters and local variables (such as loop variables, catch parameters)

@Retention

Defines how long the Annotation is retained

  • SOURCE Valid in the SOURCE file
  • The CLASS is valid in the CLASS file
  • This parameter is valid when RUNTIME is running

Retention meta – the annotation type has a unique value as a member of its values from Java. Lang. The annotation. RetentionPolicy enumeration values

@Documented

Indicates that the annotation should be logged by the Javadoc tool. By default, Javadoc does not include annotations. However, if @documented is specified when you declare an annotation, it will be handled by a tool like Javadoc (mark annotations with no member)

4. Spring IOC application

Tips. Whether it’s XML or annotations, there’s a one-to-one correspondence, just dig into one

4.1 Three IOC implementations of the Spring framework

– A – pure XML
Open means
  • JavaSE application
/ / 1
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("beans.xml");
/ / 2
new FileSystemXmlApplicationContext("c:/beans.xml");
Copy the code
  • JavaWeb application
Use the ContextLoaderListener listenerCopy the code
– b-xml + annotationsWork most commonly used
  • JavaSE application

Just like A

  • JavaWeb application

Just like A

– C – pure annotation
  • JavaSE application
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
Copy the code
  • JavaWeb application
Use the ContextLoaderListener listenerCopy the code

4.2 BeanFactory differs from ApplicationContext

To follow up

4.3 Spring IOC advanced features

To follow up

-A- Lazy-init is lazy-loaded

To follow up

-B- Rear processor

To follow up

Five, Spring IOC source in-depth analysis

“Prepare for war”

  • Current tool version:IDEA2019.3 + Spring 5.0 x + Gradle 5.6.3 + jdk8
  • Pull the source code from gitHub
  • Spring is managed using Gradle. Please install and configure it yourself

The viable version configures a complete repository

There are all kinds of problems that can be solved online. P.S. (Don’t use tools that you think are up to date)

5.1 The Spring IoC container initializes the body process

Start with a simple line of code:

// Inside the cave
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Copy the code
  • ApplicationContext is a high-level interface to the container, BeanFacotry (top/root container, which regulates/defines the basic behavior of the container)
  • ApplicationContext is a Spring application release.IoC container (a collection of components and procedures)
  • ApplicationContext has one important component — a MapSingleton pool singletonObjects
Since the BeanFactory

Spring beans projects

5.2 Key timing points in the Bean life cycle

P.S. The following two pictures from the pull box

– [A] – Bean’s no-argument construct breakpoint

Observe the call stack, starting from the test method testIoC(), with further calls to be executed

– [B] – Breakpoint in initialization method

– [C] -beanFactory Post-processor initialization/call method breakpoint

– [D] – Bean post-processor initialization breakpoint

– [E] – Bean post-processor beafore/after method breakpoint

-【 Summary 】-
  • Constructor execution, initialization method execution, Bean post-handler before/after method, :

AbstractApplicationContext–>refresh–>finishBeanFactoryInitialization

  • Bean factory post-processor initialization, method execution

AbstractApplicationContext–>refresh–>invokeBeanFactoryPostProcessors

  • Bean post-processor initialization:

AbstractApplicationContext–>refresh–>registerBeanPostProcessors

—————————— As you can see, refresh() is a very important method ——————————

5.3 Container initialization subprocess

– [forward enter] – refresh()

To enter!

5.4 BeanFactory Creation Process

Begin to enter – > ConfigurableListableBeanFactory the beanFactory = obtainFreshBeanFactory ();

  • refreshBeanFactory

  • Sequence diagram

  • LoadBeanDefinitions loadBeanDefinitions loadBeanDefinitions loadBeanDefinitions loadBeanDefinitions loadBeanDefinitions

5.5 Bean creation process

To follow up

5.6 Principles of the lazy-init lazy loading mechanism

To follow up

5.7 “Difficulties in P7” Spring IoC cycle dependency

The kernel idea

Sequence diagram

Six, Spring AOP application

AOP essence: to enhance crosscutting logic without changing the original business logic, crosscutting logic code is often permission verification code, logging code, transaction control code, performance monitoring code

Let’s pull out the red box code:

6.1 Related Terms

6.1.1 Joinpoint

– Refers to points that can be used to add enhanced code to the business thread. In the figure above, the dots refer to methods. Add enhanced code before and after method execution through dynamic proxy techniques.

In the technical implementation of the Spring Framework AOP idea, only method type join points are also supported

6.1.2 Pointcut

– Refers to join points where enhanced code has been added to the business mainline.

6.1.3 Advice (Notification/enhancement)

– refers to the methods used in the aspect class to provide enhanced functionality.

– The timing of enhancement varies with different methods:

  • The transaction must be started before the business method is executed;
  • Commit transactions are executed after the normal execution of the business method;
  • Rollback transactions are executed after business method execution generates an exception;
  • .
6.1.4 Target

– Refers to the target object of the proxy. That is, the proxied object

6.1.5 Proxy

– Refers to a proxy class created when a class is woven into AOP for enhancement. The proxy object

Weaving (Weaving)

– Refers to the process of applying an enhancement to a target object to create a new proxy object.

  • Spring uses dynamic proxy weaving;
  • AspectJ uses compile-time weaving and class-load weaving.
6.1.5 Aspect = pointcut + enhancement

– refers to the aspects that the enhanced code focuses on, and defines those related enhancements into a class called the aspect class.

6.2 How does Spring Select a Proxy Type?

By default, Spring chooses whether to use JDK or CGLIB based on whether the proxied object implements an interface.

  • Spring selects CGLIB when the proxied object does not implement any interface
  • When the proxied object implements the interface, Spring selects the JDK’s official proxy technology

Spring can be configured to enforce the use of CGLIB.

6.3 AOP configuration in Spring

As with IoC, three approaches are supported:

  1. Pure XML
  2. XML + annotation
  3. Pure annotations

6.4 Implementation of AOP in Spring (XML Schema)

– [A] – Import jar packages
<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-aop</artifactId>
 <version>5.1.12. RELEASE</version>
</dependency> <dependency>
 <groupId>org.aspectj</groupId>
 <artifactId>aspectjweaver</artifactId>
 <version>1.9.4</version>
</dependency>
Copy the code
– [B] – Core configuration
  1. theNotify the BeanTurn it over to Spring
  2. useaop:configEnable the CONFIGURATION of AOP
  3. useaop:aspectThe configuration section
  4. Configure the notification type using the corresponding label
<! Preparation for Spring's XML-based AOP configuration: In the spring configuration file to join aop constraints XMLNS: aop = "http://www.springframework.org/schema/aop" http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd-->

<! Give the notification bean to Spring to manage
<bean id="logUtil" class="com.lagou.utils.LogUtil"></bean>
<! Start aop configuration -->
<aop:config>
<! -- Configuration section -->
 <aop:aspect id="logAdvice" ref="logUtil">
 <! -- Configure pre-notification -->
 <aop:before method="printLog" pointcut="execution(public *com.lagou.service.impl.TransferServiceImpl.updateAccountByCardNo(com.lagou.pojo.Account))"></aop:before>
 </aop:aspect>
</aop:config>
Copy the code
– [supplement] – Pointcut expressions &AspectJ

A string that follows a particular syntactic structure and is used to enhance syntactic join points. (It is part of an AspectJ expression.)

AspectJ is an AOP framework based on the Java language. The Spring framework has supported AspectJ pointcut expressions since version 2.0 by integrating parts of the AspectJ framework with pointcut expressions.

– [Supplement] – Five notification types
  • Pre noticeaop:before

Can only appear inside the AOP :aspect tag Method: the method name used to specify the pre-advice Pointcut: used to specify pointcut expressions Pointcut-ref: reference used to specify pointcut expressions Pre-advice takes and enhances the arguments of a pointcut method

  • Notification during normal executionaop:after-returning

Can only appear inside the AOP :aspect tag Method: the method name used to specify post-advice Pointcut: used to specify pointcut expressions pointcut-ref: used to specify a reference to a pointcut expression

  • Abnormal noticeaop:after-throwing

Pointcut: pointcut: pointcut: pointcut-ref: reference used to specify pointcut expressions Exception advice can not only retrieve the parameters of a pointcut method execution, You can also get exception information generated by the execution of the pointcut method

  • Final noticeaop:after

Can only appear inside the AOP :aspect tag Method: the method name used to specify the final advice Pointcut: used to specify pointcut expressions Pointcut-ref :a reference used to specify pointcut expressions When the final advice is executed, the parameters of the advice method can be retrieved. It can also do some cleaning

  • Surrounding the notificationaop:around

Method: used to specify the name of the method that surrounds the advice pointcut: used to specify pointcut expressions Pointcut-ref: used to specify references to pointcut expressions The first four (pre, post, exception, and final) are all notification types that specify when to enhance. Surround notification, on the other hand, is a type of notification that the Spring framework provides to control, through coding, when enhanced code is executed. It uses the ProceedingJoinPoint interface and its implementation class to manually trigger the invocation of pointcut methods

6.5 Support for declarative transactions

With follow up

Seven, Spring AOP source analysis

To follow up