【Spring注解系列09】Spring初始化和销毁接口-InitializingBean与DisposableBean

1.InitializingBean与DisposableBean

InitializingBean

定义初始化逻辑,用于执行自定义初始化或者校验已设置的属性值等。

* Interface to be implemented by beans that need to react once all their properties
* have been set by a {@link BeanFactory}: e.g. to perform custom initialization,
* or merely to check that all mandatory properties have been set.

DisposableBean

定义销毁逻辑,用于一个实例bean销毁后需要释放资源等。 只有bean从容器中移除或者销毁或容器关闭时,才会调用该方法。

ApplicationContext关闭时,默认对所有单例bean都会调用这个方法。

* Interface to be implemented by beans that want to release resources on destruction.
* A {@link BeanFactory} will invoke the destroy method on individual destruction of a
* scoped bean. An {@link org.springframework.context.ApplicationContext} is supposed
* to dispose all of its singletons on shutdown, driven by the application lifecycle.

2.实例

//实现InitializingBean,DisposableBean接口的bean
public class BeanLife implements InitializingBean,DisposableBean{

    public BeanLife() {
        System.out.println("BeanLife--->construct...");
    }


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

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


//配置类
@Configuration
public class BeanLifeCycleConfig {

   
    @Bean(value = "beanLife")
    public BeanLife life() {
        return new BeanLife();
    }
}


//测试
public class BeanLifeCycleTest {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanLifeCycleConfig.class);
        System.out.println("applicationContext ..... 初始化结束");

        System.out.println("applicationContext ..... 准备关闭");
        applicationContext.close();
        System.out.println("applicationContext ..... 已关闭");

    }
}


测试结果:
BeanLife--->construct...
BeanLife--->InitializingBean.afterPropertiesSet
applicationContext ..... 初始化结束

applicationContext ..... 准备关闭
BeanLife--->DisposableBean.destroy
applicationContext ..... 已关闭

 

你可能感兴趣的:(Spring,Spring)