[Spring] Bean scope and life cycle details: Please briefly describe the execution process of Spring and analyze the life cycle of Bean?

foreword

 We all know that the Spring framework provides developers with a lot of convenience, which enables developers to focus more on the core business logic of the application without spending a lot of time and energy on technical details. As an IoC container containing many tools and methods, accessing JavaBean is an extremely important link. This article expands on the scope and life cycle of beans in Spring in detail, hoping to help readers~
facial expression 01



1 Question introduction

 First, we create a Student class as a Bean. Bean is stored through the student in the StudentBean class with @Bean annotation. The StudentController then in turn accesses the bean and then modifies it.
 Finally, the bean is accessed again through the StudentAdviceController. Observe whether the Bean accessed by StudentAdviceController is the value before the StudentController modifies the Bean.
case structure

Expected result: We hope that the modification of the Bean by the StudentController will not affect the access of the Bean by the StudentAdviceController, but it is counterproductive~

StudentBean

@Component
public class StudentBean {
    
    

    @Bean
    public Student student() {
    
    
        Student student = new Student();
        student.setName("黄小黄");
        student.setAge(17);
        student.setGender("男");
        return student;
    }
}

StudentController

@Controller
public class StudentController {
    
    

    @Autowired
    private Student student;

    public void printStudent() {
    
    
        System.out.println("studentController | student: " + student);
        Student s = student;
        s.setName("李大明");
        System.out.println("studentController 修改后: " +student);
    }
}

StudentAdviceController

@Controller
public class StudentAdviceController {
    
    

    @Autowired
    private Student student;

    public void printStudent() {
    
    
        System.out.println("studentAdviceController | student: " + student);
    }
}

main method

    public static void main(String[] args) {
    
    
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        StudentController studentController =
                context.getBean("studentController", StudentController.class);
        StudentAdviceController studentAdviceController =
                context.getBean("studentAdviceController", StudentAdviceController.class);
        studentController.printStudent();
        studentAdviceController.printStudent();
    }

The results of the case
result 1
show that after the studentController modifies the Bean, the studentAdviceController accesses the modified Bean, which is inconsistent with expectations. In order to meet expectations, we also need to understand the scope of beans in Spring~


2 Bean scope

2.1 Scope and 6 scopes of Bean

What is scope?

Scope (Scope) refers to the area that can be accessed when defining variables in a programming language. Scope specifies the visibility and access rights of variables, that is, when a variable or function is defined, the variable or function can be accessed in the code area. In different programming languages, the specific implementation of scope may be slightly different. Common scopes include global scope, function scope, block-level scope, etc.

And what we say, the scope of the Bean refers to a certain behavior pattern of the Bean in the entire framework of Spring
Emoticon 2

When the Spring container initializes a Bean instance, it also specifies the scope of the instance. Spring has 6 scopes, and the last four are based on Spring MVC. For the first 4 types, you need to focus on mastering, and you can understand the latter two~

  1. singleton: Singleton scope (by default). Beans under this scope only have one instance in the IoC container. Usually stateless beans use this scope. Stateless means that the property status of the Bean object does not need to be updated.
  2. prototype: Prototype scope (multi-instance scope) creates a new instance every time a request for a bean under this scope is made. That is, getting and assembling Bean are instances of new objects. Usually stateful beans use this scope.
  3. request: request scope. Each http request will create a new bean instance, an http request and response shared bean.
  4. session: session scope In an http session, define a bean instance
    , which is a shared bean of the user session. For example: record a user's login information, shopping cart information, etc.
  5. application: Global scope Defines a Bean instance in an http servlet Context. The context information of the web application, such as: recording the shared information of an application.
  6. websocket: HTTP WebSocket scope defines a Bean instance in the life cycle of an HTTP WebSocket. In each session of WebSocket, the header information of a Map structure is saved, which will be used to wrap the client message header. After the first
    initialization, it is the same bean until the end of the WebSocket.

What is the difference between singleton scope and global scope?
Singleton scope means that in the container, each bean will only be created once, and all requests will return the same instance. The global scope is different from the singleton scope. In the global scope, after the Bean is created once, it will be shared and used in the context of the entire application, that is, each request returns the same instance.
Singleton scope is suitable for beans with less state or no state, such as data manipulation tool classes, service layers, controllers, etc. The global scope is suitable for beans that need to be shared among multiple applications and multiple threads, such as thread pools, connection pools, etc. But since the global scope can negatively affect the performance of the application, it should not be abused. Therefore, when using the global scope, you should think carefully before deciding to use it.

  • singleton is the scope of Spring Core; application is the scope of Spring Web
  • Singleton acts on the IoC container, while application acts on the Servlet container.

2.2 Setting scope in Spring

We can use @Scopethe tag to declare the scope of the bean.
@ScopeLabels can modify both methods and classes, and there are two ways to set them. Here is an example of setting the scope to prototype:

  1. Set the value directly: @Scope("prototype")
  2. Use enum settings: @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

2.3 Modify the code in the case

Just set the scope of the Bean in the case to prototype~

The modified StudentBean code is as follows:

@Component
public class StudentBean {
    
    

    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    @Bean
    public Student student() {
    
    
        Student student = new Student();
        student.setName("黄小黄");
        student.setAge(17);
        student.setGender("男");
        return student;
    }
}

operation result

So far, the running results have met expectations, that is, the modification of the Bean by Class A will not affect the reading of the Bean by B~


3 Spring execution process and Bean life cycle

3.1 Spring execution process

The execution process of Spring is roughly as follows:
start the Spring container -> complete the initialization of the Bean according to the configuration -> register the Bean in the Spring container (save operation) -> assemble the Bean into the required class (fetch operation)
Spring execution process

3.2 Bean life cycle and common problems

The life cycle refers to the whole process of an object from creation to destruction. The life cycle of the Bean mentioned here refers to the complete process of the Bean from creation to use to destruction.

  1. Instantiation (corresponding to "loading" in JVM): From scratch, convert bytecode into objects in memory, just allocate memory eg: bought a rough house
  2. Set properties (Bean injection and assembly) eg: purchase decoration materials (introduce external resources)
  3. Initialization eg: Renovation of the house
    a) Various notifications eg: Call each decoration master to carry out the construction
    b) Pre-initialization work eg: The master arrives at the site, surveys the environment first, and formulates a decoration plan, such as measuring the area of ​​the house, etc. ~
    c) Perform initialization work (two ways: annotation or xml. Use annotation@PostConstructinitialization, use (xml)init-methodinitialization) eg: Two types of masters for decoration: plumbers, bricklayers, electricians, etc.
  4. Use Bean eg: the house can live
  5. Destroying Bean eg: Selling a House

The specific diagram is as follows:
Bean life cycle

question1. What is the difference between Bean instantiation and Bean initialization?
Answer: Bean instantiation and bean initialization are different phases in the bean life cycle that the Spring container handles.

  • Bean instantiation refers to the process of creating a Bean instance by the Spring container, that is, according to the configured Bean definition, class information, and constructor, a Bean instance is created and put into the container for management. This process includes instantiating beans, calling constructors, injecting dependencies, and more.
  • Bean initialization refers to the process that the Spring container invokes a specific method to initialize and configure the Bean after the Bean instance is created. These specific methods can be custom methods or initialization methods provided by Spring, such as the afterPropertiesSet() method of the InitializingBean interface and the @PostConstruct annotation. At this stage, you can configure some properties for the Bean, call some initialization methods, and so on.

question2. Why set properties first and then initialize?
Answer: In the life cycle of the Bean, the property is set first and then initialized, because in the Spring IoC container, the creation and initialization of the Bean is divided into two stages, namely, the instantiation and property injection stage of the Bean, and the initialization stage of the Bean. In the instantiation phase, the Spring IoC container will first create an instance object of the Bean, but the properties of the Bean have not been injected yet. Next, the Spring IoC container calls the Bean's set method to inject property values. When all properties are injected, the Spring IoC container executes the bean's initialization method. Therefore, set the properties first and then initialize.


write at the end

This article is included in the JavaEE programming road点击订阅专栏 and is being updated continuously.
 The above is the whole content of this article! Creation is not easy, if you have any questions, welcome to private message, thank you for your support!

insert image description here

Guess you like

Origin blog.csdn.net/m0_60353039/article/details/131498949