Abstract: When using Spring for IOC configuration, the configuration and use of beans has always been a more important part. At the same time, how to use and create bean objects reasonably is also a part that friends need to pay attention to when learning and using Spring. , So in this article, I will tell you about the scope and life cycle of beans in Spring.

This article is shared from the HUAWEI CLOUD community " the Scope and Life Cycle of Bean in Spring ", the original author: Gray Little Ape.

When using Spring for IOC configuration, the configuration and use of beans have always been a more important part. At the same time, how to use and create bean objects reasonably is also the part that friends need to pay attention to when learning and using Spring, so this In this article, I will tell you about the scope and life cycle of beans in Spring.

One, the scope of Bean

First, let’s talk about the scope of beans,

Under normal circumstances, the configuration information we write in the IOC container will be created when our IOC container is running. This leads to the fact that when we obtain bean objects through the IOC container, we often obtain single-instance Bean objects.

This means that no matter how many getBean() methods we use, the same JavaBean obtained is the same object, which is a single-instance Bean, and the entire project will share this bean object.

In Spring, you can set the scope of the bean in the scope attribute of the <bean> element to determine whether the bean is single-instance or multi-instance. Scope attribute has four parameters, the specific usage can be seen in the figure below:
image.png

1. Single-instance Bean declaration

By default, Spring only creates a unique instance for each bean declared in the IOC container, which can be shared across the entire IOC container: all subsequent getBean() calls and bean references will return this unique bean instance . This scope is called singleton, and it is the default scope for all beans. That is, single instance.

To verify this statement, we create a single-instance bean in the IOC, and obtain the bean object for comparison:

<!-- singleton单实例bean
  1、在容器创建时被创建
  2、只有一个实例
  -->
<bean id="book02" class="com.spring.beans.Book" scope="singleton"></bean>

Test whether the obtained single-instance beans are the same:

@Test
public void test09() {
    // 单实例创建时创建的两个bean相等
    Book book03 = (Book)iocContext3.getBean("book02");
    Book book04 = (Book)iocContext3.getBean("book02");
    System.out.println(book03==book04);
}

The result obtained by

2. Multi-instance Bean declaration

And since there is a single instance, there must be multiple instances. We can set the prototype parameter for the scope property of the bean object to indicate that the instance is multi-instance, and at the same time obtain the multi-instance bean in the IOC container, and then compare the obtained multi-instance beans.

<!-- prototype多实例bean
1、在容器创建时不会被创建,
2、只有在被调用的时候才会被创建
3、可以存在多个实例
 -->
<bean id="book01" class="com.spring.beans.Book" scope="prototype"></bean>

Test whether the obtained multi-instance bean is the same:

@Test
public void test09() {
    // 多实例创建时,创建的两个bean对象不相等
    Book book01 = (Book)iocContext3.getBean("book01");
    Book book02 = (Book)iocContext3.getBean("book01");
    System.out.println(book01==book02);
}

The result is false

This shows that the bean objects created through multiple instances are different.

needs attention here:

At the same time, there are also differences in the creation of single-instance and multi-instance beans. When the scope of the bean is singleton, Spring will create the object instance of the bean when the IOC container object is created. When the scope of the bean is prototype, the IOC container creates an instance object of the bean when it obtains the instance of the bean.

Second, the life cycle of Bean

1. Initialization and destruction of bean

In fact, every bean object we create in the IOC has a specific life cycle. The life cycle of the bean can be managed in the Spring IOC container. Spring allows the specified task to be performed at a specific point in the bean life cycle. Such as the method executed when the bean is initialized and the method executed when the bean is destroyed.

Spring IOC container manages the bean's life cycle process can be divided into six steps:

  1. Create bean instance through constructor or factory method
  2. Set values for bean properties and references to other beans
  3. Call the bean's initialization method
  4. The bean can be used normally
  5. When the container is closed, call the destruction method of the bean

So how to declare the methods that are executed when the bean is initialized and destroyed?

First of all, we should add methods to be executed when the bean class is initialized and destroyed. Such as the following javabean:

package com.spring.beans;

public class Book {
    private String bookName;
    private String author;
    /**
     * 初始化方法
     * */
    public void myInit() {
        System.out.println("book bean被创建");
    }
 
    /**
     * 销毁时方法
     * */
    public void myDestory() {
        System.out.println("book bean被销毁");
    }
 
    public String getBookName() {
        return bookName;
    }
    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    @Override
    public String toString() {
        return "Book [bookName=" + bookName + ", author=" + author + "]";
    }
}

At this time, when we configure the bean, we can specify the initialization and destruction methods for the bean through the init-method and destroy-method attributes.

<!-- 设置bean的生命周期
destory-method:结束调用的方法
init-method:起始时调用的方法
 -->
<bean id="book01" class="com.spring.beans.Book" destroy-method="myDestory" init-method="myInit"></bean>

So that when we create and destroy bean objects through the IOC container, the corresponding methods will be executed.

But there is one thing to note here:

As we said above, the creation time of a single-instance bean and a multi-instance bean are different, so the execution time of their initial method and destruction method is slightly different.

  • The life cycle of a bean under a single instance

Container start -> initialization method -> (container closed) destruction method

  • The life cycle of a bean under multiple instances

Container start -> call bean -> initialization method -> container shutdown (the destruction method is not executed)

2. Bean's post processor

What is a bean's post processor? bean post-processor allows call longitudinal initializer for additional processing bean

The bean post processor processes all bean instances in the IOC container one by one, rather than a single instance.

Its typical application is to check the correctness of bean properties or change bean properties according to specific standards.

The bean post processor needs to implement the interface when using:

org.springframework.beans.factory.config.BeanPostProcessor。
Before and after the initialization method is called, Spring will pass each bean instance to the following two methods of the above interface:

postProcessBeforeInitialization(Object, String) before calling
postProcessAfterInitialization(Object, String) after calling
The following is a post processor implemented in this interface:

package com.spring.beans;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * 测试bean的后置处理器
 * 在这里要注意一点是为了出现bean和beanName,而不是arg0、arg1,需要绑定相应的源码jar包
 * */
public class MyBeanPostProcessor implements BeanPostProcessor{

    /**
     * postProcessBeforeInitialization
     * 初始化方法执行前执行
     * Object bean
     * String beanName xml容器中定义的bean名称
     * */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        // TODO Auto-generated method stub
        System.out.println("【"+ beanName+"】初始化方法执行前...");
        return bean;
    }

    /**
     * postProcessAfterInitialization
     * 初始化方法执行后执行
     * Object bean
     * String beanName xml容器中定义的bean名称
     * */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        // TODO Auto-generated method stub
        System.out.println("【"+ beanName+"】初始化方法执行后...");
        return bean;
    }

}

Add the post processor to the IOC container:

<!-- 测试bean的后置处理器 -->
<bean id="beanPostProcessor" class="com.spring.beans.MyBeanPostProcessor"></bean>

Since our bean object is single-instance now, the bean object will be created directly when the container is running, and the post-processor method and initialization method of the bean will be executed at the same time, and the destruction method will be executed when the container is destroyed. We tested as follows:

//*************************bean生命周期*****************
//    由于ApplicationContext是一个顶层接口,里面没有销毁方法close,所以需要使用它的子接口进行接收
    ConfigurableApplicationContext iocContext01 = new ClassPathXmlApplicationContext("ioc1.xml");
 
    @Test
    public void test01() {
        iocContext01.getBean("book01");
        iocContext01.close();
    }

operation result:
image.png
image.png

summarize the execution process of the post processor:

  1. By constructing or factory method create bean instance
  2. Set the value and references to other beans for the
  3. Pass the bean instance to the postProcessBeforeInitialization() method of the bean post processor
  4. Call the bean's initialize the method
  5. Pass the bean instance to the postProcessAfterInitialization() method of the bean post processor
  6. bean can be used
  7. Call the bean's destruction method when the container is closed

So the life cycle of the bean after adding the bean post processor is:

Container start-before... of the post processor -> initialization method-> after... of the post processor--> (container closed) destruction method

Click to follow, and get to know the fresh technology of


华为云开发者联盟
1.4k 声望1.8k 粉丝

生于云,长于云,让开发者成为决定性力量