Step by step analysis of spring bean life cycle

Keywords: Java xml Spring Attribute

The life cycle of spring beans is the basis and difficulty for further study of spring. This article will elaborate the life cycle of spring beans in the way of code + graphic conclusion.

This article will clarify the following figure.

 

I. Project structure and source code

1. Program directory structure

 2.applicationContext.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 class="com.demo.dao.UserDao" id="userDao" scope="singleton" init-method="myInit" destroy-method="myDestroy">
        <property name="userName" value="Alan_beijing"/>
    </bean>

    <bean class="com.demo.dao.MyBeanPostProcessor" id="myBeanPostProcessor"/>

</beans>

3.UserDao.java

package com.demo.dao;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.apache.log4j.Logger;

public class UserDao implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean,
        DisposableBean{

    private String userName;
    private int count = 0;

    public String getUserName() {
        return userName;
    }

    //2.Attribute injection, which injects attributes as userName
    public void setUserName(String userName) {
        count++;
        System.out.println(count + ": Injection attribute userName="+userName);
        this.userName = userName;
    }

    //1.A parametric constructor that is called when instantiated
    public UserDao() {
        count++;
        System.out.println(count + ": Call the constructor UserDao()");
    }

    //3.Realization BeanNameAware,Obtain bean id
    public void setBeanName(String s) {
        count++;
        System.out.println(count + ": call setBeanName()Obtain bean id,bean id=" + s);
    }

    //4.Realization BeanFactoryAware,Obtain bean factory
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        count++;
        System.out.println(count + ": call setBeanFactory()Obtain bean factory,beanFactory=" + beanFactory);
    }

    //5.Realization ApplicationContextAware,Obtain bean context
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        count++;
        System.out.println(count + ": call setApplicationContext()Obtain bean context,applicationContext=" + applicationContext);
    }

    //6.Realization InitializingBean,Obtain afterPropertiesSet
    public void afterPropertiesSet() throws Exception {
        count++;
        System.out.println(count + ": call afterPropertiesSet()");
    }

    //7.Custom initialization method myInit()
    public void myInit() {
        count++;
        System.out.println(count + ": Call Customization myInit()");
    }

    //8.Realization DisposableBean,Obtain destroy()
    public void destroy() throws Exception {
        count++;
        System.out.println(count + ": destroy()");
    }

    //9.Custom Destruction Method myDestroy()
    public void myDestroy() {
        count++;
        System.out.println(count + ": Call Customization destroy()");
    }
}
4.MyBeanPostProcessor.java
package com.demo.dao;

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

public  class MyBeanPostProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("=====call postProcessBeforeInitialization()=====");
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("=====call postProcessAfterInitialization()=====");
        return bean;
    }
}

2. Test code and test results

1.test.java

package com.demo.test;

import com.demo.dao.UserDao;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {

    @Test
    public void test() {
        //Define containers and initialize them
        //ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        AbstractApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        applicationContext.getBean(UserDao.class);
        //Only when the container is closed will it be called destroy Method
        applicationContext.registerShutdownHook();
    }
}

2. Test results

Three analysis

Based on the above test results, the bean life cycle process is roughly as follows:

 

1. Assembly bean s

Bean assembly is the first step in the bean life cycle. Assembly beans refer to the process of converting java objects into beans. In this example, UserDao.jave and MyBeanPostProcessor are transformed into beans through xml.

Note: The spring framework supports four ways of assembling bean s: xml, java code, automatic and hybrid assemblies

2. Load applicationContext.xml and instantiate it

Loading and instantiating beans is the second step in the bean life cycle. This example loads and loads through ClassPathXml Application Context (), which instantiates objects without waiting when the bean is singleton

The object is instantiated only when the application Context. getBean () is called to get the bean, which is different from prototype.

3. Attribute injection

Bean attribute injection is the third step of bean life cycle, and beans are injected by reflection.

 

4. Implement BeanNameAware to get bean id

This process is the fourth part of the bean life cycle. The implementation of this interface can obtain the id of the bean.

 

5. Implement BeanFactoryAware to get the bean factory

This process is the fifth part of the bean life cycle, by implementing BeanFactoryAware to obtain the bean factory

6. Implementing Application Context Aware to obtain application context

This process is the sixth part of the bean life cycle. Through the implementation of the Application ContextAware interface, the bean context can be obtained.

7. Call Bean Post Processor before

This process is the seventh part of the bean life cycle. It obtains before and after by implementing the post processor BeanPost Processor. This process is implemented by AOP. Between before and after, the following 8,9 processes occur.

8. Implement the afterPropertiesSet() of InitializingBean to get the initialization method

This process is the eighth part of the bean life cycle. After Properties Set () is obtained by implementing Initializing Bean.

9. Call custom initialization method, init-method

This process is the ninth link of the bean life cycle, which implements the customized initialization method.

10. Call Bean Post Processor after

This process is the tenth part of the bean life cycle and the last part of the post-processor.

11. Close the container AbstractApplicationContext.registerShutDownHook()

This is the eleventh link in the bean life cycle, closing the container

 

12. Call destroy() of Disposable Bean

This process is the twelfth link of the bean life cycle. It implements the Disposable Bean interface and calls destroy().

13. Call the customized destroy-method

This process is the last step in the bean life cycle, calling the custom destroy-method

3. Copyright Zone

  • To reprint a blog, the source of the blog must be indicated.
  • Blogger's website: http://www.cnblogs.com/wangjiming/
  • If you have any new ideas, please send them to 2098469527@qq.com.
  • Professional. NET Home Technology QQ Group: 490539956
  • Specialized Java House QQ Group: 924412846
  • QQ group: 2098469527
  • One-to-one technical guidance QQ: 2098469527

Posted by zenabi on Sun, 13 Oct 2019 10:20:41 -0700