Spring Series - Bean Life Cycle

Table of contents

Classic interview questions:

1. Bean life cycle diagram

2. Introduction to the Bean life cycle process:

Three, Bean singleton and multi-case mode

Summarize:


Foreword: What Xiaobian brings to you today is an explanation of the Bean life cycle in the Spring series. Before understanding the life cycle of Bean, it is recommended to read the explanation of Spring's AOP first. I hope that everyone who read it can bring effective help to your study and work! Spring http://t.csdn.cn/N0Fp4 http://t.csdn.cn/N0Fp4

Classic interview questions:

Question 1: "Does the Spring container manage the initialization process of JavaBean?"

Answer: "The first step: configure JavaBean in [xml, configuration annotation, annotation configuration class]

          Step 2: Parse the JavaBean in the BeanDefinitionReader to generate the BeanDefinition, and traverse through the list collection.

           Step 3: Go to BeanFactoryPostProcessor, JavaBean executes its own business.

           The fourth step: beanFactory in spring, initialize all Javabean objects through the list collection.

           Step 5: If your own JavaBean needs to call resources in the spring context, you need to implement the *Aware perception interface.

           Step 6: If your own JavaBean has been initialized, you need to extend it. Use BeanFactoryPostProcessor to complete.

Question 2: "Is JavaBean in Spring a singleton or multiple instance pattern?"

Answer: "First: JavaBean in Spring is a singleton mode by default, but it can be configured as a multi-instance mode. Because: this is related to the characteristics of the singleton mode: the characteristics of a singleton: save memory resources, and variables are easy to pollute. Multiple instances Features: It takes up a lot of resources, and variables are not easily polluted. "  

         Second: Singleton mode: JavaBean is initialized with the context "Multiple instance mode: JavaBean is created when it is used, and it is destroyed following"

          Third: The second point is not absolute.

1. Bean life cycle diagram

Understanding: Spring's life cycle mainly refers to creation, initialization, and destruction . The life cycle of the bean is mainly managed by the container. We can customize the initialization and destruction methods of the bean. The container calls the custom initialization and destruction methods at a specific point in the life cycle of the bean.

2. Introduction to the Bean life cycle process:

1. Load spring beans through XML, Java annotation and Java Configuration

2. BeanDefinitionReader : Parse the definition of Bean . During the startup process of the Spring container, the Bean will be parsed into the BeanDefinition structure inside Spring; this process is somewhat similar to the instantiated modeling object.

3. BeanDefinition: How many attributes and methods are included, such as class name, scope, attribute, constructor parameter list, dependent bean, whether it is a singleton, whether it is lazy loading, etc. In fact, it is to store the definition information of the Bean in the corresponding attribute of the BeanDefinition, and then directly operate the BeanDefinition on the Bean. For example, after getting the BeanDefinition, you can use it according to the class name, constructor, and constructor parameters inside Reflection does object creation.

Idea: By looking at the original code of beandefinition, we found that this class has been defined and encapsulated its own class name, constructor, and constructor parameters, so we get this object and we go to traverse the object that can get the instance according to the principle of reflection

   

4. BeanFactoryPostProcessor: It is an important interface to realize the function extension of spring container , such as modifying bean property value, realizing bean dynamic proxy, etc. Many frameworks implement the extension of the spring container through this interface. For example, when mybatis integrates with spring, only the mapper interface is defined, and there is no implementation class, but spring can complete automatic injection.

   > Note:
   > 1) BeanFactoryPostProcessor is executed after the spring container loads the BeanDefinition and before the bean is instantiated;
   > 2) Processes the bean metadata (BeanDefinition), that is, BeanDefinition property filling, modification, etc.;

If you want to perform operations such as non-null verification on a certain property in a bean (custom operation), you can implement the interface class
BeanFactoryPostProcessor to complete the extension function.

5. BeanFactory: Bean factory. According to our requirements, it produces all kinds of beans we need and provides them for us to use. Only in the process of bean production, the dependency problem between beans needs to be solved, and the technology of dependency injection (DI) is introduced. That is to say, dependency injection is a technique for resolving dependencies between beans when beanFactory produces beans.

6) Aware-aware interface: In actual development, it is often necessary to use the functional resources of the Spring container itself

For example: BeanNameAware, ApplicationContextAware, etc.

BeanDefinition implements BeanNameAware, ApplicationContextAware

7) BeanPostProcessor: post processor. After the Bean object is instantiated and introduced and injected,

Add custom logic before and after calling the initialization method. (Similar to AOP's wrap around advice)

Precondition: If it is detected that the Bean object implements the BeanPostProcessor post processor, it will be executed

Before and After methods

BeanPostProcessor

1)Before

2) Call the initialization bean (InitializingBean and init-method, the initialization of the bean is considered complete)

3)After

Completed the creation of the Bean

8) destroy: destroy

Introduce the words in the life cycle of Bean in detail

1 BeanDefinitionReader
In Spring, BeanDefinitionReader is a class used to read and parse configuration files, which plays an important role in the life cycle of JavaBean.

In the life cycle of JavaBean, BeanDefinitionReader is mainly used in the instantiation and attribute injection phases. It reads the <bean> tag in the configuration file, and parses information such as property values, initialization methods, and destruction methods. By parsing the configuration file, BeanDefinitionReader can obtain metadata such as the class name, attribute value, initialization method and destruction method of JavaBean.

In the instantiation phase, BeanDefinitionReader will use the reflection mechanism to create an instance of JavaBean according to the information in the configuration file. It will obtain the class name of the JavaBean according to the class attribute in the <bean> tag in the configuration file, and use the reflection mechanism to create an instance of the JavaBean.

In the attribute injection phase, BeanDefinitionReader will obtain the attribute value of JavaBean according to the <property> tag in the configuration file, and use the reflection mechanism to inject the attribute value into JavaBean. It will obtain the property name according to the name attribute in the <property> tag in the configuration file, then obtain the corresponding property value according to the name property, and use the reflection mechanism to inject the property value into the JavaBean.

In addition to the instantiation and property injection phase, BeanDefinitionReader can also play a role in other phases. For example, in the initialization phase, BeanDefinitionReader can read the init-method attribute in the configuration file and call it as the initialization method. During the destruction phase, BeanDefinitionReader can read the destroy-method attribute in the configuration file and call it as the destruction method.

In short, BeanDefinitionReader plays a role in parsing and reading configuration files in the life cycle of JavaBean. It can obtain the metadata of JavaBean, and perform operations such as instantiation, property injection, initialization and destruction according to the information in the configuration file.

2 BeanDefinition
BeanDefinition is an important concept in the Spring framework, which is used to describe and define the information of a Bean.

Specifically, the role of BeanDefinition mainly has the following aspects:

1. Define Bean properties: BeanDefinition defines the properties of a Bean, including the Bean's class name, scope, lazy loading, dependencies, etc. Through BeanDefinition, Bean properties can be configured and managed.
2. Describe the dependencies of Beans: BeanDefinition describes the dependencies between Beans and other Beans. It can specify other beans that the bean depends on, as well as the way of dependence (such as through constructor injection, setter method injection, etc.). Through BeanDefinition, dependency injection between beans can be realized.
3. Define Bean initialization and destruction methods: BeanDefinition can define Bean initialization methods and destruction methods. It can specify the initialization method that the bean needs to execute after instantiation, and the destruction method that needs to be executed before it is destroyed. Through BeanDefinition, the management of Bean life cycle can be realized.
4. Extend the function of Bean: Through BeanDefinition, the definition of Bean can be extended to realize custom functions. Bean can be enhanced by adding AOP aspects, transaction management and other functions in BeanDefinition.
5. Flexible configuration of Bean definition: BeanDefinition provides a flexible configuration method, which can define beans through XML configuration files, annotations or programming. You can choose an appropriate way to configure the Bean definition according to your needs.
In short, BeanDefinition is an important concept used to describe and define Bean information in the Spring framework. It defines Bean properties, dependencies, initialization and destruction methods and other information, which can realize the configuration and management of Beans. Through BeanDefinition, flexible Bean configuration and extension can be realized, so as to realize the customized function of Bean.

3 BeanFactoryPostProcessor
BeanFactoryPostProcessor is an extension interface in the Spring framework, which can modify or extend the definition of the Bean after the Spring container instantiates the Bean.

Specifically, the role of BeanFactoryPostProcessor mainly has the following aspects:

1. Modify the definition of the Bean: By implementing the BeanFactoryPostProcessor interface, the definition of the Bean can be modified before the Spring container instantiates the Bean. Bean property values, scopes, dependencies, etc. can be added, deleted, or modified. In this way, the definition of Bean can be dynamically adjusted without modifying the source code.
2. Extend the definition of the Bean: By implementing the BeanFactoryPostProcessor interface, the definition of the Bean can be extended before the Spring container instantiates the Bean. You can add new bean definitions, or implement custom extension functions by modifying bean definitions. For example, functions such as AOP aspect and transaction management can be added to the Bean definition.
3. Configure the property value of the Bean: By implementing the BeanFactoryPostProcessor interface, you can configure the property value of the Bean before the Spring container instantiates the Bean. Bean property values ​​can be dynamically set according to needs, so as to achieve more flexible configuration.
4. Parse and process Bean definition: The BeanFactoryPostProcessor interface can also be used to parse and process Bean definition. Bean definitions can be parsed and processed as needed to implement specific logic. For example, other relevant bean definitions can be generated according to the bean definition, or some logical judgments and processing can be performed according to the bean definition.
It should be noted that the BeanFactoryPostProcessor modifies or extends the definition of the Bean after the Spring container instantiates the Bean. The difference between it and the BeanPostProcessor interface is that BeanFactoryPostProcessor operates in the definition phase of Bean, while BeanPostProcessor operates in the instantiation and initialization phase of Bean. Therefore, BeanFactoryPostProcessor can modify the definition of Bean, while BeanPostProcessor can only operate on Bean instances.

4 BeanFactory
BeanFactory is one of the core interfaces in the Spring framework, which is a factory for managing and obtaining Bean instances.

Specifically, the role of BeanFactory mainly has the following aspects:

1. Instantiate Bean: BeanFactory is responsible for instantiating JavaBean according to configuration files or annotations. It will use the reflection mechanism to create a JavaBean instance according to the <bean> tag in the configuration file or the configuration information in the annotation. Through BeanFactory, you can easily create and obtain various types of Bean instances.
2. Manage the life cycle of Bean: BeanFactory manages the life cycle of Bean. It creates instances of the bean when needed and destroys instances of the bean when not needed. Through BeanFactory, you can control the process of Bean creation, initialization and destruction, and realize flexible management of Bean.
3. Inject dependencies: BeanFactory is responsible for injecting dependencies between beans into Bean instances. It will inject the dependent Bean into the target Bean according to the <property> tag in the configuration file or the dependency in the annotation. Through BeanFactory, dependency injection between beans can be realized, so as to realize a loosely coupled design.
4. Provide the Bean access interface: BeanFactory provides the Bean access interface, which can easily obtain the instantiated Bean. Through BeanFactory, the corresponding Bean instance can be obtained according to the name or type of the Bean. In this way, Bean can be conveniently used in the application to realize various functions.
In short, BeanFactory is the core interface used to manage and obtain Bean instances in the Spring framework. It is responsible for instantiating beans, managing the life cycle of beans, injecting dependencies, and providing bean access interfaces. It is an important part of implementing IoC (inversion of control) and DI (dependency injection) in the Spring framework.

5 Aware
Aware is a set of interfaces in the Spring framework, which is used to inject specific resources or callback interfaces into the Bean during the Bean instantiation process.

Specifically, the Aware interface mainly has the following functions:

1. Provide access to the Spring container: By implementing the ApplicationContextAware interface, the Bean can obtain a reference to the Spring container. In this way, various functions of the Spring container can be directly accessed in the bean, such as obtaining other beans, obtaining environment variables, and so on.
2. Provide access to the BeanFactory: By implementing the BeanFactoryAware interface, the Bean can obtain a reference to the BeanFactory. In this way, various functions of the BeanFactory can be directly accessed in the Bean, such as obtaining the definition of the Bean, obtaining the properties of the Bean, and so on.
3. Provide access to the name of the Bean: By implementing the BeanNameAware interface, the Bean can obtain its own name in the Spring container. In this way, you can get your own name in the Bean and do some specific processing.
4. Provide access to resources: By implementing the ResourceLoaderAware interface, the Bean can obtain a reference to the resource loader. In this way, resources can be loaded directly in the Bean, such as reading configuration files, accessing files, and so on.
5. Provide access to the message source: By implementing the MessageSourceAware interface, the Bean can obtain a reference to the message source. In this way, the source of the message can be directly accessed in the bean to realize the functions of internationalization and localization.
By implementing these Aware interfaces, the Bean can obtain the relevant resources or callback interfaces of the Spring container, so as to access or use these resources. In this way, some specific functions can be realized more conveniently in the Bean, and the flexibility and scalability of the system can be improved.
 

Three, Bean singleton and multi-case mode

        Comparison of single case and multiple case mode

        The characteristics of a single case: save resources, and variables are easy to pollute.
        The characteristics of multiple cases: it takes up a lot of resources, and the variables are not easy to be polluted.

Run through the demo code:

The main advantages and benefits of using the singleton pattern in Spring include:

1. Saving resources: The singleton mode can ensure that only one instance exists in the entire application, saving the overhead of system resources. Each request returns the same instance, avoiding the overhead of repeatedly creating objects.
2. Improve performance: Since the singleton mode only creates one instance, it avoids the overhead of frequently creating and destroying objects, thereby improving the performance of the system.
3. Avoid race conditions: In a multi-threaded environment, using the singleton pattern can prevent multiple threads from accessing and modifying the state of the object at the same time, thus avoiding the problems of race conditions and data inconsistency.
4. Unified management and coordination of resources: The singleton mode can manage and coordinate shared resources in the system in a unified manner to ensure the correct use and release of resources and avoid resource leakage and waste.
5. Provide a global access point: The singleton mode can provide a global access point, which is convenient for other objects or modules to obtain instances through this access point, which simplifies the use and invocation of objects.
6. Simplified configuration and management: In the Spring framework, defining a Bean as a singleton pattern can simplify configuration and management. It only needs to be declared as a singleton in the configuration file or annotation, and the Spring container is responsible for creating and managing the singleton object.
In general, the advantages of using singleton mode in Spring include saving resources, improving performance, avoiding race conditions, unified management and coordination of resources, providing global access points, and simplifying configuration and management. These advantages make Spring perform well in large-scale applications and high-concurrency environments, and provide better scalability and maintainability.
 

In the Spring framework, the multi-case pattern (Prototype Pattern) means that a new instance is created every time an object instance is obtained. Compared with the singleton pattern, the multi-case pattern has the following advantages and benefits:

1. Flexibility: The multi-instance mode can create multiple instances according to requirements, and each instance can have different states and attributes, providing greater flexibility and customization.
2. Avoid shared state: The multi-instance pattern creates a new instance each time, avoiding the problem of shared state between multiple objects. Each instance is independent and does not affect each other.
3. High concurrency performance: In a high concurrency environment, the multi-instance mode can reduce thread competition and improve the concurrency performance of the system. Each thread obtains an independent instance, and there will be no resource competition.
4. Avoid the disadvantages of the singleton mode: In some scenarios, the singleton mode may have disadvantages such as thread safety issues and excessive resource occupation, while the multi-instance mode can avoid these problems.
5. Reduce the degree of coupling: The multi-instance pattern can reduce the degree of coupling between objects. Each object is independent and can be created and destroyed independently without excessive dependencies.
6. Provide flexible life cycle management: The multi-instance mode can manage the creation and destruction of instances through the life cycle management function of the Spring container, providing a more flexible life cycle management method.
It should be noted that the multi-instance mode also has some potential problems. For example, the creation and destruction of objects is expensive, which may affect system performance; the multi-instance mode may lead to excessive creation of objects and occupy too many system resources. Therefore, when using the multi-instance mode, trade-offs and choices need to be made according to specific business scenarios and performance requirements.
 

1.spring.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">


    <bean id="paramAction" class="com.zking.beanLife.ParamAction" scope="prototype">
        <constructor-arg name="name" value="牛妈肥镖"></constructor-arg>
        <constructor-arg name="age" value="21"></constructor-arg>
        <constructor-arg name="hobby">
            <list>
                <value>抽烟</value>
                <value>玩及</value>
                <value>彩笔</value>
            </list>
        </constructor-arg>
    </bean>

    <bean id="instanceFactory" class="com.zking.beanLife.InstanceFactory"
          scope="prototype" init-method="init" destroy-method="destroy"></bean>
</beans>

2. Demo test class

package com.zking.beanLife;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/*
 * spring	bean的生命週期
 * spring	bean的單例多例
 */
public class Demo2 {
	// 体现单例与多例的区别
	@Test
	public void test1() {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring.xml");
//		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
		ParamAction p1 = (ParamAction) applicationContext.getBean("paramAction");
		ParamAction p2 = (ParamAction) applicationContext.getBean("paramAction");
		 System.out.println(p1==p2);
		p1.execute();
		p2.execute();

//		单例时,容器销毁instanceFactory对象也销毁;多例时,容器销毁对象不一定销毁;
		applicationContext.close();
	}

	// 体现单例与多例的初始化的时间点 instanceFactory
	@Test
	public void test2() {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring.xml");
	}

	// BeanFactory会初始化bean对象,但会根据不同的实现子类采取不同的初始化方式
	// 默认情况下bean的初始化,单例模式立马会执行,但是此时XmlBeanFactory作为子类,单例模式下容器创建,bean依赖没有初始化,只有要获取使用bean对象才进行初始化
	@Test
	public void test3() {
		// ClassPathXmlApplicationContext applicationContext = new
		// ClassPathXmlApplicationContext("/spring-context.xml");

		Resource resource = new ClassPathResource("/spring.xml");
		BeanFactory beanFactory = new XmlBeanFactory(resource);
//		InstanceFactory i1 = (InstanceFactory) beanFactory.getBean("instanceFactory");

	}

}

Here, the singleton mode can be changed to multi-case mode as long as it is specified in spring.xml

Demonstration effect:

Singleton mode running result:

 Multi-instance mode operation results: 

3. Applicable scenarios of singleton mode and multi-instance mode
Singleton mode and multi-instance mode have different applicability in different scenarios. The following are common applicable scenarios for them:

Scenarios suitable for singleton mode:

Resource sharing: When the same resource or data needs to be shared among multiple components of the application, the singleton mode can ensure global data consistency.
Factory class: When it is necessary to create a global factory class to uniformly manage the creation and life cycle of objects, the singleton mode can ensure that there is always only one instance of the factory class.
Configuration information: When a global configuration information needs to be loaded in the application and multiple components need to share the configuration information, the singleton mode can ensure the consistency and efficient access of the configuration information.
Logger: When it is necessary to use the same logger to record logs throughout the application, the singleton mode can ensure the consistency and centralized management of logs.
Scenarios suitable for multiple instances:

Concurrent request processing: When requests need to be processed in a multi-threaded or concurrent environment, and each request uses an independent instance to ensure state isolation, the multi-instance mode can create an independent object for each request.
Object pool: When it is necessary to manage a group of reusable objects, and objects need to be created and destroyed at different times, the multi-instance pattern can provide object pools to manage the life cycle of objects to reduce the overhead of creation and destruction.
State management: When the state of an object needs to be maintained and processed independently in different contexts, the multi-instance pattern can create an independent instance for each context to avoid state conflicts and mutual interference.
Service provider: When the system needs to support multiple service providers of the same type, and each service provider needs an independent instance, the multi-instance pattern can meet the creation and management requirements of the service provider.
 

Summarize:

The life cycle of the Spring framework mainly includes three stages: creation, initialization and destruction. The container manages the life cycle of the bean, and the initialization and destruction methods of the bean can be customized, and the container will call it at a specific point in time. The entire life cycle of a single instance bean can be controlled. The life cycle of Spring Bean is divided into four phases and multiple extension points. An extension point can affect the lifecycle of multiple beans or a single bean. In short, the Spring framework provides a flexible life cycle management mechanism, enabling developers to better control and customize the Bean creation and destruction process

Guess you like

Origin blog.csdn.net/m0_73647713/article/details/132361312
Recommended