Don't look for it. Answer the life cycle of Bean in Spring. Here's a summary for you

The life cycle of Bean in ApplicationContext

Here's a picture:

 

You must have been blinded to see this picture. Don't worry, I'll explain it slowly: from getBean( )To trigger points, the Spring container's Bean life cycle has gone through the life cycle in the figure, which is divided into two classes:

  • The three steps of the green arrow and the two steps of the pink arrow in the figure are container level life cycle interfaces. When Spring loads any Bean into the container, these interfaces will make several calls as shown in the figure. These two processors are called "container level postprocessors". Their impact is global and can affect all beans
  • The interface circled by the big red circle in the figure is called "factory level postprocessor". Similar interfaces include CustomEditorConfigurer,PropertyPlaceholderConfigurer, etc. these interfaces are only called once during context initialization to complete the processing of some configuration files.
  • The rest is simple. It belongs to the Bean level interface, which belongs to a Bean. Each Bean calls its own unique interface when instantiating.

It is worth mentioning that whether it is a "container level postprocessor" or a "factory level postprocessor", they can configure multiple (for example, configure two beanpostprocessors). If you want to control their call order, you can implement an org.springframework.core.Ordered interface. Of course, it's not necessary. Generally, there is only one kind of post processor.

Emphasis! :

The calling order of these interfaces is not always the same. They will change as the version of Spring changes. What we need to do is never leave the original. We know that we can do some attribute operations during Bean initialization through these interfaces. The call order should be tested according to the specific version. Here is an example:

public class Student implements BeanFactoryAware, BeanNameAware,
        InitializingBean, DisposableBean,ApplicationContextAware {
    private String name;

    public Student(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("BeanFactoryAware......");
    }

    @Override
    public void setBeanName(String s) {
        System.out.println("BeanNameAware......");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("DisposableBean......");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitializingBean......");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("ApplicationContextAware......");
    }
}

BeanFactoryPostProcessor:

public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    public MyBeanFactoryPostProcessor() {
        super();
        System.out.println("This is BeanFactoryPostProcessor Implement class constructor!!");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)
            throws BeansException {
        System.out.println("BeanFactoryPostProcessor call postProcessBeanFactory method");
        BeanDefinition bd = arg0.getBeanDefinition("student");
        MutablePropertyValues propertyValues = bd.getPropertyValues();
        //The information in the configuration file exists in the form of BeanDefinition after it is loaded into Spring. Here, BeanDefinition can be changed, so it can be understood as changing the content in the configuration file
//        propertyValues.add("zdy","123");
    }

}

BeanPostProcessor:

public class MyBeanPostProcessor implements BeanPostProcessor {

    public MyBeanPostProcessor() {
        super();
        System.out.println("This is BeanPostProcessor Implement class constructor!!");
    }

    @Override
    public Object postProcessAfterInitialization(Object arg0, String arg1)
            throws BeansException {
        System.out.println("BeanPostProcessor Interface method After Change properties!");
        return arg0;
    }

    @Override
    public Object postProcessBeforeInitialization(Object arg0, String arg1)
            throws BeansException {
        System.out.println("BeanPostProcessor Interface method Before Change properties!");
        return arg0;
    }
}

InstantiationAwareBeanPostProcessorAdapter:

public class MyInstantiationAwareBeanPostProcessor extends
        InstantiationAwareBeanPostProcessorAdapter {

    public MyInstantiationAwareBeanPostProcessor() {
        super();
        System.out.println("This is InstantiationAwareBeanPostProcessorAdapter Implement class constructor!!");
    }

    //The interface method and the instantiation of Bean are called before.
    @Override
    public Object postProcessBeforeInstantiation(Class beanClass,
                                                 String beanName) throws BeansException {
        System.out.println("InstantiationAwareBeanPostProcessor call Before method");
        return null;
    }

    //After the interface method is instantiated, Bean is called.
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println("InstantiationAwareBeanPostProcessor call Ater method");
        return bean;
    }

    //Called when interface method or setting a property
    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs,
                                                    PropertyDescriptor[] pds, Object bean, String beanName)
            throws BeansException {
        System.out.println("InstantiationAwareBeanPostProcessor call postProcessPropertyValues method");
        return pvs;
    }
}

Then our Main method:

public class App 
{
    public static void main( String[] args )
    {

        ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml");
        Student stu = (Student) ac.getBean("student");
        stu.setName("wangwu");
    }
}

Spring file is the simplest: (note that we need to add all our own defined processors to the container)

<?xml version="1.0" encoding="UTF-8"?>
<beans
    <bean id="student" class="com.zdy.Student">
        <constructor-arg value="zhangsan"/>
    </bean>
    <bean id="myBeanFactoryPostProcessor" class="com.zdy.MyBeanFactoryPostProcessor"></bean>
    <bean id="myInstantiationAwareBeanPostProcessor" class="com.zdy.MyInstantiationAwareBeanPostProcessor"></bean>
    <bean id="myBeanPostProcessor" class="com.zdy.MyBeanPostProcessor"></bean>
</beans>

Then run for a while and see the result:

This is the BeanFactoryPostProcessor implementation class constructor!!
BeanFactoryPostProcessor calls the postProcessBeanFactory method
 This is the InstantiationAwareBeanPostProcessorAdapter implementation class constructor!!
This is the implementation class constructor of BeanPostProcessor!!
InstantiationAwareBeanPostProcessor calls the Before method
 InstantiationAwareBeanPostProcessor calls the postProcessPropertyValues method
BeanNameAware......
BeanFactoryAware......
ApplicationContextAware......
BeanPostProcessor interface method Before changes properties!
InitializingBean......
InstantiationAwareBeanPostProcessor calls the Ater method
 BeanPostProcessor interface method After changes properties!

Well, I'm almost finished with the general process. I'd like to say something about Bean's life cycle: in order to expose its internal mechanism to users as much as possible, Spring adds many mechanisms in the process of Bean creation, which are exposed through the so-called "Processor" Processor, Then the processors have their own order. All we need to do is define the logic of the Processor, register it in the sprint container, and Spring will call.

Secondly, there is another way to let our Bean implement some interfaces (similar to ApplicationContextAware). In this way, at a certain step of Bean initialization, we call the methods defined by the interface to pass in some information, such as ApplicationContextAware to pass ApplicationContext to us.

Then I'll tell you a few practical knowledge points. Remember, when you use them, you can turn them over

  1. In the above life cycle flow chart, pay attention to the calling sequence to avoid the phenomenon of property coverage.
  2. BeanFactoryPostProcessor mainly performs some operations when Spring has just loaded the configuration file and has not yet initialized the bean. For example, tampering with the configuration file of a Bean.
  3. The instantiation awarebeanpostprocessor adapter is basically useless. It is called when the property value has not been set after Bean initialization. Like beanfactory postprocessor, it can tamper with the information loaded into memory by the configuration file.
  4. ApplicationContextAware: very useful, injected ApplicationContext into Bean.
  5. InitializingBean: it's useful. You can do some customization after all the Bean properties have been changed.
  6. BeanPostProcessor: it's no use. Spring framework is used fiercely inside. For example, AOP and dynamic proxy are all doing things here. Later, I have time to analyze with you.
  7. Other methods like init method and destroy method are basically decorations.. I haven't used it very much. I only know it.

epilogue

Well, Bean's life cycle is over. Actually, there's nothing. As you know, when you can use the "post processor" to do something, you can come back and see the order roughly. Secondly, there are some interfaces implemented by Bean, the most commonly used ones are (ApplicationContextAware and InitializingBean). There is BeanPostProcessor, because in the method of this interface, the Bean entity will be passed in as Object.

So you can do some operations on attributes. In fact, programmers use less. Many are used inside the frame. OK, this article is actually rough, mainly because there is nothing to talk about, Over, Have a good day!

Finally, I have compiled a set of interview materials to keep you calm during the interview

 

 

 

 

Collection steps:
1. Plus wechat access

Tags: Java Spring xml REST Attribute

Posted on Tue, 12 May 2020 05:48:07 -0400 by widox