Bean生命周期 Bean创建 -->初始化 -->销毁
1.自定义Bean初始化 和销毁的方法
init-method和destroy-method
创建Bike类
public class Bike {
public Bike(){
System.out.println("Bike Constructor...");
}
public void init(){
System.out.println("bike ...init...");
}
public void destroy(){
System.out.println("bike ....destroy...");
}
}
配置类
@Configuration
public class MainConfig {
@Bean(initMethod = "init",destroyMethod = "destroy")
public Bike bike(){
return new Bike();
}
}
测试
@Test
public void test1(){
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(MainConfig.class);
context.close();
}打印结果
Bike Constructor...
bike ...init...
十月 15, 2019 10:05:36 上午 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@5c0369c4: startup date [Tue Oct 15 10:05:35 CST 2019]; root of context hierarchy
bike ....destroy...
对于单实例的bean 可以正常调用初始化和销毁方法
对于多实例的bean( @Scope("prototype") ) 容器只负责初始化(第一次获取该bean实例时才会创建并初始化) 但不会管理bean ,容器关闭时不会调用销毁方法
单例懒加载的bean (@lazy)第一次调用时初始化bean 容器会管理
2 .实现 InitializingBean 和 DisposableBean 接口
afterPropertiesSet() 当beanFactroy 创建好对象,并且把bean所有属性设置好之后,会调用这个方法。
destroy() 当一个单例bean销毁时 BeanFactory 会调用这个销毁方法 , 在容器关闭时,应用上下文会销毁所有的单例bean。
@Component
public class Bike implements InitializingBean, DisposableBean {
public Bike(){
System.out.println("Bike Constructor...");
}
//当bean销毁时调用
public void destroy() throws Exception {
System.out.println("Bike destroy..");
}
//当bean 属性数赋值和初始化是调用
public void afterPropertiesSet() throws Exception {
System.out.println("Bike ....afterPropertiesSet...");
}
}
3. 使用JSR250 规则 定义的两个注解
@PostConstruct 在bean创建完成 ,且属性复制完成后进行初始化,属于JDK规范的注解
@PreDestroy 在bean将被移除之前进行通知,在容器晓辉之前进行清理工作
@Component
public class Bike {
public Bike(){
System.out.println("Bike Constructor...");
}
@PostConstruct
public void init(){
System.out.println("Bike...@PostConstruct...");
}
@PreDestroy
public void destroy(){
System.out.println("Bike...@@PreDestroy...");
}
}