Spring bean生命周期中的鉤子

bean自身級生命周期接口

  • 配置文件中的init-method和destroy-method方法
  • bean實(shí)現(xiàn)BeanNameAware、BeanFactoryAware、InitializingBean和DiposableBean這些接口的方法

做個(gè)實(shí)驗(yàn)看一下這些方法的調(diào)用順序

先是兩個(gè)bean

package autopackage;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class Person implements BeanFactoryAware, BeanNameAware,InitializingBean,DisposableBean {

    private Fruit fruit;

    private String name;

    public Person(String name, Fruit fruit) {
        System.out.println("I'm the Person1");
        this.name = name;
        this.fruit = fruit;
    }

    public Person(Fruit fruit) {
        System.out.println("I'm the Person2");
        this.fruit = fruit;
    }

    public void setFruit(Fruit fruit) {
        System.out.println("I'm the setFruit");

        this.fruit = fruit;
    }

    public void setName(String name) {
        System.out.println("I'm the setName");

        this.name = name;
    }

    public void init() {
        System.out.println("I'm the init");
    }

    public void destroy1() {
        System.out.println("I'm the destroy1");
    }

    public void eat() {
        System.out.println(name+"正在吃"+fruit.getName()+"...");
    }

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

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

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

    @Override
    public void destroy() {
        System.out.println("I'm the DisposableBean.destroy");
    }


}
package autopackage;

public class Fruit {
    private String name;

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

    public String getName() {
        return name;
    }
}

接著是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 id="person" class="autopackage.Person" init-method="init" destroy-method="destroy1">
        <!--<constructor-arg value="lkxiaolou" />-->
        <constructor-arg ref="fruit" />
        <property name="name" value="lkxiaolou"/>
    </bean>

    <bean id="fruit" class="autopackage.Fruit">
        <constructor-arg value="apple" />
    </bean>

</beans>

再是測試代碼

package main;

import autopackage.Person;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PersonMain {

    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("Person.xml");
        Person person = (Person) context.getBean("person");
        person.eat();
        context.registerShutdownHook();
    }
}

執(zhí)行后會(huì)發(fā)現(xiàn)輸出是這樣的:

I'm the Person2
I'm the setName
I'm the BeanNameAware.setBeanName
I'm the BeanFactoryAware.setBeanFactory
I'm the InitializingBean.afterPropertiesSet
I'm the init
lkxiaolou正在吃apple...
I'm the DisposableBean.destroy
I'm the destroy1

容器級生命周期接口方法

包括了InstantiationAwareBeanPostProcessor 和 BeanPostProcessor這兩個(gè)接口實(shí)現(xiàn),一般稱它們的實(shí)現(xiàn)類為“后處理器”,InstantiationAwareBeanPostProcessor 接口本質(zhì)是BeanPostProcessor的子接口,我們繼承Spring為其提供的適配器類InstantiationAwareBeanPostProcessor Adapter來使用它。

將上面的代碼改造一下,新建一個(gè)新類

package autopackage;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;


public class PersonBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    public PersonBeanFactoryPostProcessor() {
        System.out.println("I'm the PersonBeanFactoryPostProcessor");
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        System.out.println("I'm the PersonBeanFactoryPostProcessor.postProcessBeanFactory");
    }
}

package autopackage;

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

public class PersonBeanPostProcessor implements BeanPostProcessor {

    public PersonBeanPostProcessor() {
        System.out.println("I'm the PersonBeanPostProcessor");
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Person) {
            System.out.println("I'm the PersonBeanPostProcessor.postProcessBeforeInitialization;beanName=" + beanName);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Person) {
            System.out.println("I'm the PersonBeanPostProcessor.postProcessAfterInitialization;beanName=" + beanName);
        }
        return bean;
    }
}

package autopackage;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;

public class PersonInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {

    public PersonInstantiationAwareBeanPostProcessor() {
        super();
        System.out.println("I'm the PersonInstantiationAwareBeanPostProcessor");
    }

    @Override
    public Class<?> predictBeanType(Class<?> beanClass, String beanName) {
        return super.predictBeanType(beanClass, beanName);
    }

    @Override
    public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException {
        return super.determineCandidateConstructors(beanClass, beanName);
    }

    @Override
    public Object getEarlyBeanReference(Object bean, String beanName) throws BeansException {
        return super.getEarlyBeanReference(bean, beanName);
    }

    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if (beanClass.equals(Person.class)) {
            System.out.println("I'm the PersonInstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation");
        }
        return super.postProcessBeforeInstantiation(beanClass, beanName);
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if (bean instanceof Person) {
            System.out.println("I'm the PersonInstantiationAwareBeanPostProcessor.postProcessAfterInstantiation");
        }
        return super.postProcessAfterInstantiation(bean, beanName);
    }

    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException {
        if (bean instanceof Person) {
            System.out.println("I'm the PersonInstantiationAwareBeanPostProcessor.postProcessPropertyValues");
        }
        return super.postProcessPropertyValues(pvs, pds, bean, beanName);
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Person) {
            System.out.println("I'm the PersonInstantiationAwareBeanPostProcessor.postProcessBeforeInitialization");
        }

        return super.postProcessBeforeInitialization(bean, beanName);
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof Person) {
            System.out.println("I'm the PersonInstantiationAwareBeanPostProcessor.postProcessAfterInitialization");
        }
        return super.postProcessAfterInitialization(bean, beanName);
    }
}

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 id="person" class="autopackage.Person" init-method="init" destroy-method="destroy1">
        <!--<constructor-arg value="lkxiaolou" />-->
        <constructor-arg ref="fruit" />
        <property name="name" value="lkxiaolou"/>
    </bean>

    <bean id="fruit" class="autopackage.Fruit">
        <constructor-arg value="apple" />
    </bean>

    <bean id="instantiationAwareBeanPostProcessor" class="autopackage.PersonInstantiationAwareBeanPostProcessor"></bean>
    <bean id="beanPostProcessor" class="autopackage.PersonBeanPostProcessor"></bean>
    <bean id="beanFactoryPostProcessor" class="autopackage.PersonBeanFactoryPostProcessor"></bean>

</beans>


其他不變,再執(zhí)行一下輸出如下

I'm the PersonBeanFactoryPostProcessor
I'm the PersonBeanFactoryPostProcessor.postProcessBeanFactory
I'm the PersonInstantiationAwareBeanPostProcessor
I'm the PersonBeanPostProcessor
I'm the PersonInstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation
I'm the Person2
I'm the PersonInstantiationAwareBeanPostProcessor.postProcessAfterInstantiation
I'm the PersonInstantiationAwareBeanPostProcessor.postProcessPropertyValues
I'm the setName
I'm the BeanNameAware.setBeanName
I'm the BeanFactoryAware.setBeanFactory
I'm the PersonInstantiationAwareBeanPostProcessor.postProcessBeforeInitialization
I'm the PersonBeanPostProcessor.postProcessBeforeInitialization;beanName=person
I'm the InitializingBean.afterPropertiesSet
I'm the init
I'm the PersonInstantiationAwareBeanPostProcessor.postProcessAfterInitialization
I'm the PersonBeanPostProcessor.postProcessAfterInitialization;beanName=person
lkxiaolou正在吃apple...
I'm the DisposableBean.destroy
I'm the destroy1

總結(jié)

可以總結(jié)出整個(gè)bean的生命周期中各個(gè)鉤子執(zhí)行的順序:


bean聲明周期中鉤子運(yùn)行順序.jpg
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容