Spring5 source code analysis-basic knowledge understanding (1)

Project directory
Insert picture description here

1. Understanding of
Spring Spring framework is the most widely used framework for Java. Its success comes from ideas. Its ideas include ioc and aop (idea: the relationship between each bean and bean is unified to the SpringIOC container management).
The Spring framework is mainly composed of seven parts, namely Spring Core, Spring AOP, Spring ORM, Spring DAO, Spring Context, Spring Web and Spring Web MVC
2. The difference between Spring and traditional object management
In tradition, we use objects through New xxx() is used to instantiate objects. In the Spring framework, objects are generally created by scanning packages and annotations. In the process of creating objects, most of them use reflection mechanisms.
3. Two ways for Spring to inject beans
We first write an object (UserEntity.java)

package com.entity;

public class UserEntity {
    
    
    private String name;
    private String age;

    public void setName(String name) {
    
    
        this.name = name;
    }

    public void setAge(String age) {
    
    
        this.age = age;
    }

    @Override
    public String toString() {
    
    
        return "com.entity.UserEntity{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

And introduce dependencies in pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.20.RELEASE</version>
    </dependency>
</dependencies>
  1. xml injection
    directly create application.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 注入对象,一般使用小驼峰命名法 使用property注入对象属性值-->
    <bean id="userEntity" class="com.spring.entity.UserEntity">
        <property name="name" value="小王"/>
        <property name="age" value="18"/>
    </bean>
</beans>

Create Application.java under the com.spring package

public class Application {
    
    

    public static void main(String[] args) {
    
    
        // 解析xml配置,并指定xml文件,xml文件默认在resource根目录下
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("application.xml");
        // 获取对象
        UserEntity userEntity = classPathXmlApplicationContext.getBean("userEntity", UserEntity.class);
        System.out.println(userEntity.toString());
    }

}

Operation result:

so we can find that the data injected in xml is also printed

  1. Annotation form injection
    Create MyConfig.java under com.spring.config
package com.spring.config;

import com.spring.entity.UserEntity;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfig {
    
    
    //@Configuration 相当于创建了spring.xml
    @Bean
    public UserEntity userEntity(){
    
    
        return new UserEntity();
    }
}

Operation result: In
Insert picture description here
this way, we can also see that we have successfully created the UserEntity object.
Of course, the @Configuration annotation has many uses. For example, using @ComponentScan("com.spring") under this annotation can scan external packages, then we You can add such a piece of code to Application.java

// 获取在MyConfig中注入的所有bean
String[] beanDefinitionNames = annotationConfigApplicationContext.getBeanDefinitionNames();
for (int i = 0; i < beanDefinitionNames.length; i++) {
    
    
      System.out.println(beanDefinitionNames[i]);
}

operation result:
Insert picture description here

In this way, we have implemented two injection methods. Of course, there are various injection methods in the two injection methods, and they are not limited to the one given for example.

4. Is the object singleton or multiple instances
by default? The answer is that it is singleton by default.
Test method (add the following code in Application.java):

UserService userService1 = annotationConfigApplicationContext.getBean("userService", UserService.class);
UserService userService2 = annotationConfigApplicationContext.getBean("userService", UserService.class);
System.out.println(userService1 == userService2);

Return result:
Insert picture description here
Let us understand here that the object defaults to a singleton, so how do we want the object to become multiple instances?
It's very simple. Add @Scope("prototype") to the object that needs to be set to multiple instances

5. When the object is created, the hungry man is the hungry man or the lazy man.
Let me first explain the hungry man and the lazy man .
Hungry Chinese style: During the process of loading the configuration file, all objects are created. This is why we start tomcat very slowly every time we start it. After the startup is successful, it will soon be
lazy style: only when the object is used Will be created
Test method principle: When each object is created, it will go to a parameterless constructor
Test method:
Add a parameterless constructor in UserService.java

public UserService(){
    
    
   System.out.println("UserSerivce被创建");
}

Add code in Application.java

System.out.println("配置文件启动成功");
UserService userService1 = annotationConfigApplicationContext.getBean("userService", UserService.class);

Operation result:
Insert picture description here
This also proves that our objects are loaded in hungry style by default, so how do we configure what we want objects to be loaded in lazy style?
It’s very simple, just add an annotation @Lazy(value = true) to the object.

Guess you like

Origin blog.csdn.net/weixin_43911969/article/details/113836072