使用@Bean调用自定义的Bean初始化、销毁方法
在@Bean内部,可以指定initMethod和destroyMethod(调用bean内部的方法)
- 定义Bean:
- 增加配置类
- 测试
- 总结
对于单实例Bean
在容器关闭时,destory方法会被自动调用
实现InitializingBean和DisposableBean接口
使用JSR250:PostConstruct 、PreDestroy
@PostConstruct : 在初始化完成后调用
@PreDestroy :在Bean被移除前调用
使用BeanPostProcessor
可以在初始化前后分步处理
postProcessBeforeInitialization方法时机十分靠前,
在Bean的无参构造器调用之后调用,
在InitializingBean接口的内部方法afterPropertiesSet调用之前调用,
在JSR250规范的PostConstruct注解方法之前调用。
初始化Bean之前先要对bean进行属性填充。
populate Bean : 根据Bean定义信息,来填充Bean
initializeBean : 填充后再初始化Bean
在调用自定义init初始化方法之前,先会调用BeanPostProcessorsBeforeInitialization,而init之后则会调用BeanPostProcessorsAfterInitialization。
附:
实现其他BeanPostProcessor类型接口
package com.EzerbelCN.bean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class Bird implements DisposableBean, InitializingBean,ApplicationContextAware {
private ApplicationContext applicationContext;
public Bird() {
System.out.println("构造Bird");
}
public void afterPropertiesSet() throws Exception {
System.out.println("Bird after Properties Set");
}
public void destroy() throws Exception {
System.out.println("销毁Bird");
}
public void init_method() {
System.out.println("Bird init");
}
public void destroy_method() {
System.out.println("Bird destroy");
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}