- 前面讲了bean的创建和注入,这一节将介绍bean的生命周期。
- bean的生命周期过程:
bean创建---初始化----销毁的过程
- spring中bean的生命周期由容器管理,我们可以自定义初始化和销毁方法;容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法。
一、实现自定义初始化和销毁方法的几种方法
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实现InitializingBean和DisposableBean接口
//1、实现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创建完成并且属性赋值完成;来执行初始化方法
@PreDestroy:在容器销毁bean之前通知我们进行清理工作
public class Train {
public Train (){
System.out.println("train constructor...");
}
//对象创建并赋值之后调用
@PostConstruct
public void init(){
System.out.println("train....@PostConstruct...");
}
//容器移除对象之前
@PreDestroy
public void detory(){
System.out.println("train....@PreDestroy...");
}
}
4、BeanPostProcessor接口,bean的后置处理器
public class MyBeanPostProcessor implements BeanPostProcessor {
//在初始化之前工作(会环绕所有的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生命周期过程总结:
- 创建
- BeanPostProcessor.postProcessBeforeInitialization
- 初始化
- BeanPostProcessor.postProcessAfterInitialization
- 销毁
二、单实例和多实例对生命周期的影响
- 构建对象的时候
单实例:在容器启动的时候创建对象
多实例:在每次获取的时候创建对象
- 初始化时候
对象创建完成,并赋值好,调用初始化方法
- 销毁时候
单实例:容器关闭的时候
多实例:容器不会管理这个bean;容器不会调用销毁方法
三、BeanPostProcessor原理
- 前面知道BeanPostProcessor是一个后置处理器接口,源码:
public interface BeanPostProcessor {
//方法在初始化之前执行,
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
//方法在初始化之后执行,
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
- BeanPostProcessor接口有很多的实现了,这些实现类很多非常重要,想bean赋值,注入其他组件,@Autowired,生命周期注解功能,@Async等等功能的完成都和相应的实现了有关系。
1、ApplicationContextAwareProcessor实现类
- 继承该类,并重写相应的方法可以获取ApplicationContext对象
- 使用:
@Component
public class Train implements ApplicationContextAware {
//通过在实现ApplicationContextAware在组件bean初始化的时候传入
//ApplicationContext,这样可以根据ApplicationContext中的一些数据进行一些自定义的操作
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());
}
//实现类,在bean初始化之前执行
@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
AccessControlContext acc = null;
//判断bean是不是属性系列的aware实现类
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 {
//调用相应的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;
}
}