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

This article is shared from the Huawei Cloud Community “detailed interpretation of the scope and life cycle of beans in Spring”, the original author: Grey Monkey Monkey.

When using Spring for IOC configuration, the configuration and use of beans have always been an important part. At the same time, how to use and create bean objects reasonably is also the part that students need to pay attention to when learning and using Spring. So in this article I want to talk to you about the scope and life cycle of beans in Spring.

The scope of the Bean

First let’s talk about the scope of beans,

In general, the configuration information we write in the IoC container will be created when our IoC container is running. As a result, when we get bean objects from the IoC container, we usually get a single-instance bean object.

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

In Spring, you can set the scope of a bean in the scope attribute of the <bean> element to determine whether the bean is single-instance or multi-instance.The Scope attribute has four parameters. See the following figure for the specific use:

Single-instance Bean declaration

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

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

<! --> <bean id="book02" class=" com.spring.beans.book "scope="singleton"></bean>

Test if the obtained singleton bean is the same:

@test public void test09() {Book book03 = (Book)iocContext3.getBean("book02"); Book book04 = (Book)iocContext3.getBean("book02"); System.out.println(book03==book04); }

The result is true;

Multi-instance Bean declaration

And if there is a single instance, there must be multiple instances. We can set the prototype parameter to the scope property of the bean object to indicate that the instance is multi-instance, get the multi-instance beans in the IOC container, and compare the obtained multi-instance beans.

<! -- prototype multi-instance bean 1, not created when the container is created, >< bean id="book01" class=" com.spring.beans.book "scope="prototype"></bean>

Test if the fetched multi-instance bean is the same:

@test public void test09() {Book book01 = (Book)iocContext3.getBean("book01"); Book book02 = (Book)iocContext3.getBean("book01"); System.out.println(book01==book02); }

The result is false

This means that bean objects created through multiple instances are not the same.

Note here:

There is also a difference in the creation of singleton and multi-instance beans. When the bean is singleton scoped, Spring creates an object instance of the bean as soon as the IoC container object is created. When the scope of the bean is Prototype, the IOC container creates the instance object of the bean when it gets the instance of the bean.

The Bean life cycle

1. Bean initialization and destruction

In fact, every bean object we create in IOC has a specific life cycle. The life cycle of the bean can be managed in Spring’s IOC container. Spring allows the execution of specified tasks at specific points in the bean life cycle. Such as methods executed when the bean is initialized and methods executed when the bean is destroyed.

The Spring IoC container manages the bean lifecycle in six steps:

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

How do you declare the methods that are performed when the bean is initialized and destroyed?

First we should add the methods that are executed at initialization and destruction inside the bean class. Like the following JavaBeans:

package com.spring.beans; public class Book { private String bookName; private String author; Public void myInit() {System.out.println(" Book bean is created "); } public void myStory () {System.out.println(" Book bean is destroyed ");} public void myStory () {System.out.println(" Book bean is destroyed "); } 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 + "]"; }}

When configuring the bean, we can specify initialization and destruction methods for the bean using the init-method and destroy-method properties.

<! Destory-method: method that ends the call init-method: >< bean id="book01" class="com.spring.beans.Book" destroy-method=" myDefory "init-method="myInit"></bean>

This will execute the corresponding method when we create and destroy the bean object through the IOC container.

But there is a caveat here:

As we said above, the creation times of single-instance beans and multi-instance beans are different, so the execution times of their initial and destruction methods are slightly different.

  • The life cycle of a bean under a single instance

Container start — > initialization method — > (container close) destruction method

  • The life cycle of a bean under multiple instances

Container start — > calls bean — > initialization method — > container closed (destruction method not executed)

2, Post processor for bean

What is the bean’s post-processor? The bean post-handler allows additional processing of the bean before and after the initialization method is called

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

The typical application is to check the correctness of bean properties or to change bean properties based on a specific criteria.

The bean postprocessor needs to implement the interface for use:

Org. Springframework. Beans. Factory. Config. BeanPostProcessor. Before and after the initialization method is called, Spring passes each bean instance to the following two methods of the above interface:

PostProcessBeforeInitialization (Object, String) before invoking postProcessAfterInitialization (Object, String) calls the following is an implementation of the rear of the interface in the processor:

package com.spring.beans; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; /** * BeanName (); /** * BeanName (); /** * BeanName (); Need to bind the corresponding source jar package * * / public class MyBeanPostProcessor implements the BeanPostProcessor {/ * * * postProcessBeforeInitialization * Object bean * String beanName XML container name * */ @Override public Object postProcessBeforeInitialization(Object bean, String Beanname) throws BeansException {// TODO Auto-generated method stub System.out.println(" ["+) BeanName +"] before initializing the method..." ); return bean; PostProcessAfterInitialization} / * * * * executed after initialization method * Object String bean * beanName XML containers that are defined in the bean name * * / @ Override public Object postProcessAfterInitialization(Object bean, String Beanname) throws BeansException {// TODO Auto-generated method stub System.out.println(" ["+) BeanName +" after initialization method execution..." ); return bean; }}

Add the post-processor to the IOC container:

<! - test the bean's rear processor - > < bean id = "beanPostProcessor" class = "com. Spring. Beans. MyBeanPostProcessor" > < / bean >

Since our bean object is now singleton, the container runtime creates the bean object directly and also executes the bean’s post-handler and initializer methods, as well as the destruction method when the container is destroyed. We tested as follows:

/ / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * bean lifecycle * * * * * * * * * * * * / / because the ApplicationContext is a top-level interface, there is no destroy method close, So you need to use it a child of the interface for receiving ConfigurableApplicationContext iocContext01 = new ClassPathXmlApplicationContext (" ioc1. XML "); @Test public void test01() { iocContext01.getBean("book01"); iocContext01.close(); }

Running results:



To summarize the execution of the post-processor:

  1. Create a bean instance through a constructor or factory method
  2. Set values for bean properties and references to other beans
  3. Pass the bean instance to bean postProcessBeforeInitialization rear the processor () method
  4. Invokes the bean’s initialization method
  5. Pass the bean instance to bean postProcessAfterInitialization rear the processor () method
  6. The bean is ready to use
  7. The bean destruction method is called when the container is closed

So the life cycle of the bean after adding the bean post-handler is:

Container startup — before of the post-processor… — > initialization method — > after… > (container closed) destruction method

Click on the attention, the first time to understand Huawei cloud fresh technology ~