Hello everyone, I am the third, last session we handlifted a simple IOC container for five minutes, handlifted a Spring container! In this section, let’s take a look at the life cycle of a Bean in Spring. I find that it is really similar to a person’s life.

A few words about IoC and beans

IoC, inversion of control, we all know that the so-called inversion of control, is to give the new object to the container, all objects are controlled by the container, this is called inversion of control.

Beans, too, are nothing new; they’re just a bunch of Java objects that are involuntarily container-controlled in their lifecycle.

Bean life cycle and life

There are four phases of the Bean life cycle

As we know, there are several scopes for beans, and this article will only discuss singleton beans that are completely controlled by the IoC container.

For ordinary Java objects, their life cycle is:

  • instantiation
  • Objects are collected through garbage collection when they are no longer in use

It’s like an animal living in nature, quietly born, quietly dead.

The life cycle of a Spring Bean can be divided into four phases. After initialization, the Bean is ready for use:

  • Instantiate the Instantiation
  • Property assignment Populate
  • Initialize the Initialization
  • Destruction of Destruction

Unlike animals and humans, there are very complex societies.

Let’s see what stages people in society go through in their life. Is it similar to the life cycle of beans?

  • Birth: To be born into this world as a natural person
  • Register: register id number, name, officially become a member of human society
  • Growth: to receive education and become a useful member of society
  • Work: create value for the society
  • Death: a man dies as a lamp goes out, but when his lamp goes out, the lampstand must be buried

Beanfactory-managed beans are instantiated when they are used, and ApplicantContext-managed beans are instantiated when the container is initialized.

BeanFactory is a relatively unsound primitive society. The ApplicantContext is a developed and sound modern society.

Bean detailed life cycle

We talked about the Bean container four stages, there will be some container level, the method of front and rear of the processing, such as InstantiationAwareBeanPostProcessor, BeanPostProcessor interface methods. These methods are independent of the Bean and are registered with the Spring container for processing when the Bean is created.

It’s like, before a baby is born, you need to do something to prepare for pregnancy, to raise a fetus, to prepare for childbirth, and after the birth, you need to do some nursing. Children before and after school, also need to do some school status management.

So with the various extensions in place, let’s move on to the Bean’s detailed life cycle. First, we have a question — when does the Bean life cycle start?

For example, if the Bean is instantiated before and after, the container is initialized and the beanDefiinition is loaded.

So in this article, we take the life cycle directly from Bean instantiation, but you should also know that after Bean instantiation, you can use the post-processor to process the Bean, Such as spring BeanFactoryPostProcessor, InstantiationAwareBeanPostProcessor.

Do not worry, just like calculating the starting point of life, from the mother’s pregnancy, or from the birth of the child? We’re just taking birth here.

  • Instantiate: Step 1, instantiate a Bean object
  • Property assignment: Step 2, set the properties and dependencies for the Bean
  • Initialization: There are many steps in the initialization phase. Steps 5 and 6 are the actual initialization, steps 3 and 4 are executed before initialization, and step 7 is executed after initialization. After initialization, the Bean can be used
  • Destruction: Step 8-10, step 8 can also be counted as the destruction stage, but not in the real sense of destruction, but before using the relevant call interface of destruction registration, in order to execute the corresponding method in step 9 and 10 when the Bean is actually destroyed

We found that the detailed process of Bean life cycle is also like the process of life, birth, registration, but it is a very short thing. Grow up slowly, you have to experience a quarter of your life, and growth comes from education, whether it is school or society, before you get education, you have to register for school, when you go to school, you have to work hard… In the end, a thin piece of paper will be issued to mark us as “social people” to be hammered.

Then, forty years of service to society. Finally old and dead. But there is no retirement in the world of beans — and, perhaps, neither in the world of people.

We found that some of the intermediate extension processes can also be classified into four categories:

  • Aware interface: The Aware interface enables the Bean to get some resources of the container. For example, BeanNameAware can get BeanName. It’s like getting a scientific name before you go to school — I don’t know how many people don’t know their real name before they go to school, right? Two hairs.

  • 2. Necessary procedures and certificates/post-processors: In the life cycle of the Bean, there will be some post-processors, their role is to carry out some pre – and post-processing, such as school registration before school, after school, you will get the diploma.

  • A person may not choose how he or she is born, but he or she may choose how to live and how to die. InitializingBean and DisposableBean interfaces are used to define initialization and DisposableBean methods.

  • Four: subjective initiative/allocation of life cycle method: the environment affects people, people are also affecting the environment, the growth of serious efforts, decline can also be optimistic. You can customize initialization and destruction methods through configuration files.

The lifetime of PersonBean

Without further ado, let’s take an example of the life of the PersonBean and take a look at its flow first!

Describe the process in words:

  1. The Bean container finds the definition of the Person Bean in the configuration file, which is basically mom pregnant.
  2. The Bean container creates an instance of the Bean using the Java reflection API, and the child is born.
  3. Person declares the properties No and name, which are set to the equivalent of the registration ID number and name. If the property itself is a Bean, it is parsed and set.
  4. The Person class is implementedBeanNameAwareInterface, called by passing the name of the BeansetBeanName()Method, equivalent to a scientific name.
  5. The Person class is implementedBeanFactoryAwareInterface, called by passing an instance of the BeanFactory objectsetBeanFactory()Method, like choosing a school.
  6. The PersonBean implements the BeanPostProcessor interface and is called before initializationpostProcessBeforeInitialization()Method, equivalent to enrollment.
  7. The PersonBean class is implementedInitializingBeanInterface, after setting all the Bean properties defined in the configuration fileafterPropertiesSet()Method, like enrollment.
  8. The Bean definition in the configuration file containsinit-methodProperty, whose value will be resolved to the name of the method in the Person class, which will be called when initialized. Growth is not a process.
  9. The Bean Factory object is called if the Bean post-processor is attachedpostProcessAfterInitialization()Method, graduated, always take a card.
  10. The Person class is implementedDisposableBeanInterface, is called when the Application no longer needs the Bean referencedestroy()The method, to put it simply, is to hang up.
  11. The Person Bean definition in the configuration file containsdestroy-methodProperty, so the corresponding method definition in the Person class will be called.

Let’s look at the code!

PersonBean class

Create a PersonBean, let it implement a few special interfaces, and watch its life cycle flow.

public class PersonBean implements InitializingBean.BeanFactoryAware.BeanNameAware.DisposableBean {

    /** * ID number */
    private Integer no;

    /** * name */
    private String name;

    public PersonBean(a) {
        System.out.println(1. Call constructor: I was born!);
    }

    public Integer getNo(a) {
        return no;
    }

    public void setNo(Integer no) {
        this.no = no;
    }

    public String getName(a) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        System.out.println(2. Set properties: My name is+name);
    }

    @Override
    public void setBeanName(String s) {
        System.out.println(3. Call the BeanNameAware#setBeanName method: I'm going to school.);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println(4. Call the BeanFactoryAware#setBeanFactory method: select the school.);
    }

    @Override
    public void afterPropertiesSet(a) throws Exception {
        System.out.println("6.InitializingBean#afterPropertiesSet method: enrollment registration");
    }

    public void init(a) {
        System.out.println("7. Custom init method: Try to learn ing");
    }

    @Override
    public void destroy(a) throws Exception {
        System.out.println("9.DisposableBean#destroy method: the end of a dull life.");
    }

    public void destroyMethod(a) {
        System.out.println("10. Custom destroy method: Sleep, Don't Wake me up");
    }

    public void work(a){
        System.out.println("Bean in use: work, only those who are of no use to society have a holiday."); }}Copy the code
  • Realize InitializingBean, BeanFactoryAware, BeanNameAware, DisposableBean four interfaces
  • The no and name attributes and corresponding getter and setter methods are defined
  • Defines an instance method, work

MyBeanPostProcessor

Custom postprocessor MyBeanPostProcessor:

public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("5. BeanPostProcessor. PostProcessBeforeInitialization methods: sign up to school!");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("8. BeanPostProcessor# postProcessAfterInitialization methods: finally graduated, diploma!");
        returnbean; }}Copy the code

The configuration file

Define a configuration file spring-config.xml:

  • Using setter injection
  • Define init-method and destroy-method
<? 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 name="myBeanPostProcessor" class="cn.fighter3.spring.life.MyBeanPostProcessor" />
    <bean name="personBean" class="cn.fighter3.spring.life.PersonBean"
          init-method="init" destroy-method="destroyMethod">
        <property name="idNo" value= "80669865"/>
        <property name="name" value="Zhang Tiegang" />
    </bean>

</beans>
Copy the code

test

As a final test, observe the flow of the Life cycle of the PersonBean:

public class Main {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        PersonBean personBean = (PersonBean) context.getBean("personBean"); personBean.work(); ((ClassPathXmlApplicationContext) context).destroy(); }}Copy the code

Running results:

1.Call constructor: I was born!2.Set properties: My name is Zhang Tiegang3.Call the BeanNameAware#setBeanName method: I'm going to school4.Call the BeanFactoryAware#setBeanFactory method to select the school5.BeanPostProcessor# postProcessBeforeInitialization method: sign up to the school6.InitializingBean#afterPropertiesSet method: enrollment registration7.Custom init method: try to learn ing8.BeanPostProcessor# postProcessAfterInitialization method: finally, graduation diploma! Bean in use: work, only people who are useless to the society have a holiday.9.This is the end of a dull life10.Don't try to wake me up when I'm asleepCopy the code

Let’s see if it’s consistent with what we’ve shown here.

This article will not take you to follow up more source code, if you interested in source level of the Bean’s life cycle, can see the refresh AbstractApplicationContext class methods, this method is AplicationContext container initialization point. In this method, call the finishBeanFactoryInitialization method, this method calls the getBean method calls to the getBean method of AbstractBeanFactory getBean method.

Finally, after a few twists and turns, we arrived at our goal, the Bean creation method: DoGetBean method, in this way you can see the Bean instantiation, assignment, the initialization process, as for the ultimate destruction, can see ConfigurableApplicationContext# close ().

conclusion

At this point, the Bean lifecycle article moves on to DeStory, customizing the DeStory method — review the article’s “lifetime.”

  • The Bean life cycle can be roughly divided into four stages: instantiation, attribute assignment, initialization, destruction, and birth, registration, growth, and death.
  • There can be many extensions in the Bean life cycle, just like the trend of life, which will be affected by many factors, such as the social environment, their own choices and their own efforts.



Reference:

[1]. Spring Revealed

[2]. The Spring’s official website

[3]. Proficient in Spring4.x Enterprise Application Development Practice

[4].Spring Bean lifecycle (thoroughly illustrated with examples and source code)

[5]. Read the life cycle of Spring Beans

[6]. How to remember the life cycle of Spring Beans


Article first public number: three points evil, welcome attention!