Spirng4-快速入门之Bean的生命周期

BeanFacotry中Bean的生命周期

借用一张图来描述BeanFactory中Bean的生命周期
这里写图片描述
1.当调用者通过getBean()方法获取某一个bean时,如果容器注册了InstantiationAwareBeanPostProcessor后处理器,则会在bean实例化之前调用该接口的postProcessBeforeInstantiation(Class<?> beanClass, StribeanName)方法
2.实例化bean(一般是根据构造函数实例化,也可以根据工厂方式实例化,可自行选择)
3.如果容器实现了InstantiationAwareBeanPostProcessor接口,则会在bean实例化完成后调用该接口的postProcessAfterINstantiation()方法,然后在设置属性值之前调用该接口的postPorcessPropertyValues()方法
4.为bean实例设置默认的属性值后,如果该bean实现了BeanNameAware接口,则会在设置完属性值后,调用setBeanName()方法,将该bean的名称配置到bean中
5.如果bean实现了BeanFactoryAware接口,则会调用setBeanFacory()方法,将BeanFactory实例设置到bean中
6.如果容器装配了BeanPostProcessor后处理器,会调用该处理器的postProcessBeforeInitialization(Object bean, String beanName)方法
7.如果该bean实现了InitializingBean接口,则会调用该接口的afterPropertiesSet()方法
8.如果在<bean>里使用了init-method属性定义了初始化的方法,则此时会执行这个方法
9.如果容器装配了BeanPostProcessor后处理器,会调用该处理器的postProcessAfterInitialization(Object bean, String beanName)方法
10.如果在<bean>里指定了作用范围为scope=”prototype”,则将bean返回给调用者,由调用者负责bean后续的生命管理,Spring容器不在管理这个bean的生命周期;如果在<bean>里指定了作用范围为scope=”singleton”,则将bean放入到容器的缓存池里,并将bean返回给调用者,Spring容器继续管理这个bean的生命周期
11.对于在<bean>里指定了作用范围为scope=”singleton”的bean,当容器关闭时,会出发Spring容器对bean后续的生命的管理,如果该bean实现了DisposableBean接口,则会调用该接口的destory()方法,如果在<bean>里使用了destory-method属性定义了bean的销毁方法,则会执行这个方法,完成bean的资源释放等操作

简单的例子描述BeanFactory中Bean的生命周期

一个简单的Bean,实现了BeanFactoryAware,BeanNameAware,InitalizingBean,DisposableBean接口

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

    private String brand;
    private String color;
    private String maxSpeed;

    private BeanFactory beanFactory;
    private String beanName;

    public NewCar() {
        System.out.println("调用NewCar的默认构造函数");
    }

    public void setBrand(String brand) {
        System.out.println("调用setBrand()设置属性");
        this.brand = brand;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public void setMaxSpeed(String maxSpeed) {
        this.maxSpeed = maxSpeed;
    }

    public void introduce() {
        System.out.println("brand:" + this.brand + ";color:" + this.color + ";maxSpeed:" + this.maxSpeed);
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("调用DisposableBean.destory()方法");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("调用InitialzingBean.afterPropertiesSet()方法");
    }

    @Override
    public void setBeanName(String name) {
        System.out.println("调用BeanFactoryAware.setBeanName()方法");
        this.beanName = name;
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("调用BeanFactoryAware.setBeanFactory()方法");
        this.beanFactory = beanFactory;
    }

    public void myInit() {
        System.out.println("调用init-method所指定的myInit(),将maxSpeed设置为240");
        this.maxSpeed = "240";
    }

    public void myDestory() {
        System.out.println("调用destroy-method所指定的myDestory()");
    }
}

InstantiationAwareBeanPostProcessor的实现类,Spring提供了一个适配类InstantiationAwareBeanPostProcessorAdapter,可以通过集成这个类来实现InstantiationAwareBeanPostProcessor后处理器

public class MyInstantiationAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter{

    //在实例化bean之前调用
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if("newCar".equals(beanName)) {
            System.out.println("InstantiationAware BeanPostProcessor.postProcessBeforeInitialization()");
        }
        return null;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if("newCar".equals(beanName)) {
            System.out.println("222InstantiationAware BeanPostProcessor.postProcessBeforeInitialization()");
        }
        return bean;
    }

    //在实例化bean后调用
    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if("newCar".equals(beanName)) {
            System.out.println("InstantiationAware BeanPostProcessor.postProcessAfterInitialization()");
        }
        return true;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if("newCar".equals(beanName)) {
            System.out.println("222InstantiationAware BeanPostProcessor.postProcessAfterInitialization()");
        }
        return bean;
    }

    //在设置某个属性时调用
    @Override
    public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, Object bean,
            String beanName) throws BeansException {
        if("newCar".equals(beanName)) {
            System.out.println("InstantiationAware BeanPostProcessor.postProcessPropertyValues()");
        }
        return pvs;
    }
}
这里需要注意的是,InstantiationAwareBeanPostProcessor是BeanPostProcessor的子接口,所以上面的实现类中会有两个postProcessBeforeInstantiation和postProcessAfterInstantiation方法
//在实例化bean之前调用
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        if("newCar".equals(beanName)) {
            System.out.println("InstantiationAware BeanPostProcessor.postProcessBeforeInitialization()");
        }
        return null;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if("newCar".equals(beanName)) {
            System.out.println("222InstantiationAware BeanPostProcessor.postProcessBeforeInitialization()");
        }
        return bean;
    }
    //在实例化bean后调用
    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        if("newCar".equals(beanName)) {
            System.out.println("InstantiationAware BeanPostProcessor.postProcessAfterInitialization()");
        }
        return true;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if("newCar".equals(beanName)) {
            System.out.println("222InstantiationAware BeanPostProcessor.postProcessAfterInitialization()");
        }
        return bean;
    }
可以根据参数的不同区分,前者会在bean实例化之前和之后执行,后者会在上面描述的第6步和第9步执行

BeanPostProcessor的实现类

public class MyBeanPostPorcessor implements BeanPostProcessor{

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if("newCar".equals(beanName)) {
            NewCar newCar = (NewCar) bean;
            System.out.println("调用BeanPostProcessor.postProcessBeforeInitialization,把newCar的颜色改为绿色");
            newCar.setColor("绿色");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if("newCar".equals(beanName)) {
            NewCar newCar = (NewCar) bean;
            System.out.println("调用BeanPostProcessor.postProcessAfterInitialization,把newCar的速度改为300");
            newCar.setMaxSpeed("300");
        }
        return bean;
    }

}

配置文件bean.xml

  <!-- init-method指定初始化时调用的方法,destory-method指定销毁时调用的方法 -->
  <bean id="newCar" class="com.spring4.chpter4.NewCar" init-method="myInit" destroy-method="myDestory" scope="singleton">
    <property name="brand" value="NEW棉花糖黄金版"></property>
    <property name="color" value="黄色"></property>
    <property name="maxSpeed" value="150"></property>
  </bean>

Bean生命周期的测试类

public class BeanLifeCycle {
    private static void LifeCycleInBeanFactory() {
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource resource = resolver.getResource("classpath:com/spring4/chpter4/bean.xml");
        BeanFactory factory = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) factory);
        reader.loadBeanDefinitions(resource);

        //向容器中注入MyInstantiationAwareBeanPostProcessor后处理器
        ((ConfigurableBeanFactory)factory).addBeanPostProcessor(new MyInstantiationAwareBeanPostProcessor());

        //向容器中注入MyBeanPostProcessor后处理器
        ((ConfigurableBeanFactory)factory).addBeanPostProcessor(new MyBeanPostPorcessor());

        //第一次从容器中获取bean,容器会实例化该bean,引发bean级的生命周期方法的调用
        NewCar newCar = factory.getBean("newCar",NewCar.class);
        newCar.introduce();
        newCar.setColor("红色");

        //第二次获取bean,直接从缓存池中获取
        NewCar newCar2 = factory.getBean("newCar",NewCar.class);

        //查看newCar和newCar2是否指向同一引用
        System.out.println(newCar == newCar2);

        //关闭容器
        ((DefaultListableBeanFactory)factory).destroySingletons();

    }

    public static void main(String[] args) {
        LifeCycleInBeanFactory();
    }
}

执行结果如下:
这里写图片描述

ApplicationContext中Bean的生命周期

Bean在AppliationContext中的生命周期和在BeanFactory中类似,不同的是如果该Bean实现了ApplicationContextAware接口,则会增加一个调用该接口setApplicationContext()方法的步骤,具体流程如下图
这里写图片描述
可参考上面BeanFactory中Bean的生命周期
描述ApplicationContext中Bean的生命周期的实例
BeanFactoryPostProcessor实现类

public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor{

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

        System.out.println("调用BeanFactoryPostProcessor.postProcessBeanFactory方法");
    }

}

bean.xml配置文件

<!-- init-method指定初始化时调用的方法,destory-method指定销毁时调用的方法 -->
  <bean id="newCar" class="com.spring4.chpter4.NewCar" init-method="myInit" destroy-method="myDestory" scope="singleton">
    <property name="brand" value="NEW棉花糖黄金版"></property>
    <property name="color" value="黄色"></property>
    <property name="maxSpeed" value="150"></property>
  </bean>

  <!-- 下面3个Bean会在ApplicationContext启动时自动被识别,并注册到容器中 -->
  <bean id="myBeanFactoryPostProcessor" class="com.spring4.chpter4.MyBeanFactoryPostProcessor"></bean>

  <bean id="myBeanPostPorcessor" class="com.spring4.chpter4.MyBeanPostPorcessor"></bean>

  <bean id="myInstantiationAwareBeanPostProcessor" class="com.spring4.chpter4.MyInstantiationAwareBeanPostProcessor"></bean>

Bean生命周期的测试类

public class ApplicationLifeCycle {
    private static void LifeCycleInApplicationContext() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath*:com/spring4/chpter4/bean.xml");

        //实例化bean
        NewCar newCar = context.getBean("newCar",NewCar.class);
        newCar.introduce();

        //关闭容器
        context.close();
    }

    public static void main(String[] args) {
        LifeCycleInApplicationContext();
    }
}

执行结果如下:
这里写图片描述

最后有个问题

使用下面这种方式无法为ApplicationContext容器注册后处理器,求知道的大神指导

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath*:com/spring4/chpter4/bean.xml");

        //向容器中注入MyBeanFactoryPostProcessor后处理器
        context.addBeanFactoryPostProcessor(new MyBeanFactoryPostProcessor());

        //向容器中注入MyInstantiationAwareBeanPostProcessor后处理器
        context.getBeanFactory().addBeanPostProcessor(new MyInstantiationAwareBeanPostProcessor());

        //向容器中注入MyBeanPostProcessor后处理器
        context.getBeanFactory().addBeanPostProcessor(new MyBeanPostPorcessor());
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值