Spring4g---管理Bean的生命周期

Bean的生命周期简介

Spring4g---管理Bean的生命周期

处理单个Bean的生命周期

  • 要对单个Bean的生命周期作处理,首先需要子Bean的程序类中两个方法,作为处理Bean的初始化和销毁时的处理操作.

  • 方法的名称不重要,可以随意取,但是必须在Bean的配置文件中明确指定初始化时使用哪个方法,销毁时使用哪个方法

  • 示例:处理单个Bean的生命周期

  • 创建Cycle程序类

    private String info;

    /**
     * 进行Cycle的初始化操作,
     * 当IOC容器初始化该Bean的实例的时候,执行该方法
     */
    public void init(){
        System.out.println("init()方法开始执行");
    }

    /**
     * 当Bean被销毁的时候,执行的操作
     */
    public void destroy(){
        System.out.println("destroy()方法开始执行");
    }
//getter和setter方法
  • 配置cycle.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">

    <!--使用init-Method 指定Bean的初始化方法
        使用destroy-method 指定Bean的销毁方法-->
    <bean id="cycle" class="mao.shu.Cycle.Cycle"
          init-method="init" 
          destroy-method="destroy">
        <property name="info" value="生命周期测试"/>
    </bean>
</beans>
  • 测试
package mao.shu.cycle;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CycleTest {
    private ApplicationContext applicationContext;
    @Before
    public void before(){
        this.applicationContext = new ClassPathXmlApplicationContext("mao/shu/cycle/cycle.xml");

    }
    @Test
    public void test(){
        Cycle cycle = (Cycle) this.applicationContext.getBean("cycle");
        System.out.println(cycle.getInfo());
    }
    @After
    public void after(){
        ((ClassPathXmlApplicationContext)this.applicationContext).close();
    }

}
  • 执行结果

Spring4g---管理Bean的生命周期

处理所有的Bean的生命周期(使用Bean后置处理器)

  • 使用Bean的后置处理器完成对所有Bean的统一初始化和销毁处理操作

Spring4g---管理Bean的生命周期

  • 示例:简单实现后置处理器
package mao.shu.cycle;

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

public class BeanInitialUtil implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
        System.out.println("初始化Bean类名:"+s);
        return o;
    }

    @Override
    public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
        System.out.println("销毁Bean类名:"+s);
        return o;
    }
    
}

  • 在cycle.xml文件中配置后置处理器
  • IOC容器会自动辨别后置处理器
 <!--配置Bean后置处理器-->
 <bean class="mao.shu.cycle.BeanInitialUtil"/>
  • 再次启动测试程序
  • 可以发现后置处理器的初始化方法和销毁方法都比Bean类中自定义的初始化和销毁方法要先执行.

Spring4g---管理Bean的生命周期

添加 Bean 后置处理器后 Bean 的生命周期

Spring4g---管理Bean的生命周期