- 前面講了bean的創(chuàng)建和注入,這一節(jié)將介紹bean的生命周期徒探。
- bean的生命周期過程:
bean創(chuàng)建---初始化----銷毀的過程
- spring中bean的生命周期由容器管理瓦呼,我們可以自定義初始化和銷毀方法;容器在bean進(jìn)行到當(dāng)前生命周期的時(shí)候來調(diào)用我們自定義的初始化和銷毀方法测暗。
一央串、實(shí)現(xiàn)自定義初始化和銷毀方法的幾種方法
1、通過@Bean指定init-method和destroy-method
//1偷溺、定義bean類
public class Car {
public Car(){
System.out.println("car constructor...");
}
public void init(){
System.out.println("car ... init...");
}
public void detory(){
System.out.println("car ... detory...");
}
}
//2蹋辅、配置類中
@Bean(initMethod="init",destroyMethod="detory")
public Car car(){
return new Car();
}
2、Bean實(shí)現(xiàn)InitializingBean和DisposableBean接口
//1挫掏、實(shí)現(xiàn)InitializingBean和DisposableBean接口
public class Bus implements InitializingBean,DisposableBean {
public Bus(){
System.out.println("bus constructor...");
}
//DisposableBean接口的方法,定義銷毀邏輯
public void destroy() throws Exception {
System.out.println("bus...destroy...");
}
//InitializingBean接口的方法秩命,定義初始化邏輯
public void afterPropertiesSet() throws Exception {
System.out.println("bus...afterPropertiesSet...");
}
}
//2尉共、配置文件注入bean
@Bean
public Bus bus() {
return new Bus();
}
3、使用@PostConstruct和@PreDestroy注解
@PostConstruct:在bean創(chuàng)建完成并且屬性賦值完成弃锐;來執(zhí)行初始化方法
@PreDestroy:在容器銷毀bean之前通知我們進(jìn)行清理工作
public class Train {
public Train (){
System.out.println("train constructor...");
}
//對(duì)象創(chuàng)建并賦值之后調(diào)用
@PostConstruct
public void init(){
System.out.println("train....@PostConstruct...");
}
//容器移除對(duì)象之前
@PreDestroy
public void detory(){
System.out.println("train....@PreDestroy...");
}
}
4袄友、BeanPostProcessor接口,bean的后置處理器
public class MyBeanPostProcessor implements BeanPostProcessor {
//在初始化之前工作(會(huì)環(huán)繞所有的bean)
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization..."+beanName+"=>"+bean);
return bean;
}
//在初始化之后工作
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization..."+beanName+"=>"+bean);
return bean;
}
}
bean生命周期過程總結(jié):
- 創(chuàng)建
- BeanPostProcessor.postProcessBeforeInitialization
- 初始化
- BeanPostProcessor.postProcessAfterInitialization
- 銷毀
二霹菊、單實(shí)例和多實(shí)例對(duì)生命周期的影響
- 構(gòu)建對(duì)象的時(shí)候
單實(shí)例:在容器啟動(dòng)的時(shí)候創(chuàng)建對(duì)象
多實(shí)例:在每次獲取的時(shí)候創(chuàng)建對(duì)象
- 初始化時(shí)候
對(duì)象創(chuàng)建完成剧蚣,并賦值好,調(diào)用初始化方法
- 銷毀時(shí)候
單實(shí)例:容器關(guān)閉的時(shí)候
多實(shí)例:容器不會(huì)管理這個(gè)bean旋廷;容器不會(huì)調(diào)用銷毀方法
三鸠按、BeanPostProcessor原理
- 前面知道BeanPostProcessor是一個(gè)后置處理器接口,源碼:
public interface BeanPostProcessor {
//方法在初始化之前執(zhí)行饶碘,
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
//方法在初始化之后執(zhí)行目尖,
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
- BeanPostProcessor接口有很多的實(shí)現(xiàn)了,這些實(shí)現(xiàn)類很多非常重要扎运,想bean賦值瑟曲,注入其他組件饮戳,@Autowired,生命周期注解功能洞拨,@Async等等功能的完成都和相應(yīng)的實(shí)現(xiàn)了有關(guān)系扯罐。
1、ApplicationContextAwareProcessor實(shí)現(xiàn)類
- 繼承該類烦衣,并重寫相應(yīng)的方法可以獲取ApplicationContext對(duì)象
- 使用:
@Component
public class Train implements ApplicationContextAware {
//通過在實(shí)現(xiàn)ApplicationContextAware在組件bean初始化的時(shí)候傳入
//ApplicationContext篮赢,這樣可以根據(jù)ApplicationContext中的一些數(shù)據(jù)進(jìn)行一些自定義的操作
private ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
- 源碼
class ApplicationContextAwareProcessor implements BeanPostProcessor {
private final ConfigurableApplicationContext applicationContext;
private final StringValueResolver embeddedValueResolver;
/**
* Create a new ApplicationContextAwareProcessor for the given context.
*/
public ApplicationContextAwareProcessor(ConfigurableApplicationContext applicationContext) {
this.applicationContext = applicationContext;
this.embeddedValueResolver = new EmbeddedValueResolver(applicationContext.getBeanFactory());
}
//實(shí)現(xiàn)類,在bean初始化之前執(zhí)行
@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
AccessControlContext acc = null;
//判斷bean是不是屬性系列的aware實(shí)現(xiàn)類
if (System.getSecurityManager() != null &&
(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
acc = this.applicationContext.getBeanFactory().getAccessControlContext();
}
if (acc != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareInterfaces(bean);
return null;
}
}, acc);
}
else {
//調(diào)用相應(yīng)的aware繼承類
invokeAwareInterfaces(bean);
}
return bean;
}
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof Aware) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
return bean;
}
}