Spring注解-LifeCycle-InitializingBean、DisposableBean
InitializingBean、DisposableBean均为接口
InitializingBean
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.beans.factory;
//InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候会执行该方法。
//在属性设置完成以后会调用该方法
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
总结:
- spring为bean提供了两种初始化bean的方式,实现InitializingBean接口,实现afterPropertiesSet方法,或者在配置文件中同过init-method指定,两种方式可以同时使用 ,
执行有先后顺序,afterPropertiesSet先执行,init-method后执行 - 实现InitializingBean接口是直接调用afterPropertiesSet方法,比通过反射调用init-method指定的方法效率相对来说要高点。但是init-method方式消除了对spring的依赖
- 如果调用afterPropertiesSet方法时出错,则不调用init-method指定的方法。
- 思路用与判断某类是否加载,否则抛出异常 and 接入点AOP idea 也不错哦
DisposableBean
package org.springframework.beans.factory;
public interface DisposableBean {
//由BeanFactory在销毁单例上调用。
void destroy() throws Exception;
}
类文件
@Component
public class Cat implements InitializingBean,DisposableBean {
public Cat(){
System.out.println("cat constructor...");
}
@Override
public void destroy() throws Exception {
// TODO Auto-generated method stub
System.out.println("cat...destroy...");
}
@Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
System.out.println("cat...afterPropertiesSet...");
}
}
配置类
/**
* bean的生命周期:
* bean创建---初始化----销毁的过程
* 容器管理bean的生命周期;
* 我们可以自定义初始化和销毁方法;容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法
*
*
* 1)、指定初始化和销毁方法;
* 通过@Bean指定init-method和destroy-method;
* 2)、通过让Bean实现InitializingBean(定义初始化逻辑),
* DisposableBean(定义销毁逻辑);
*
*/
@ComponentScan("com.atguigu.bean")
@Configuration
public class MainConfigOfLifeCycle {
}
测试类
public class IOCTest_LifeCycle {
@Test
public void test01(){
//1、创建ioc容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
System.out.println("容器创建完成...");
//applicationContext.getBean("car");
//关闭容器
applicationContext.close();
}
}
运行结果
cat constructor...
cat...afterPropertiesSet...
十二月 02, 2019 3:48:26 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@1996cd68: startup date [Mon Dec 02 15:48:26 CST 2019]; root of context hierarchy
容器创建完成...
cat...destroy...
备注:
如果示例bean不是单例,而是多例bean,它的生命周期不归Spring容器来管理,这里的InitializingBean、DisposableBean中的方法是由Spring容器来调用的,所以如果一个多例实现了这两个接口是没有啥意义的,因为相应的方法根本不会被调用,当然在XML配置文件中指定了init和destroy方法,也是没有意义的。