Spring bean生命周期(下)

Spring Bean初始化前阶段

Bean的初始化可以分为前阶段,中阶段和后阶段。在初始化前阶段已经,已经完成的有:

  • 已完成:
    • Bean实例化(分为实例化前阶段,实例化阶段,实例化后阶段)
    • Bean属性赋值(赋值前阶段,赋值阶段)
    • Bean Aware接口回调(初始化阶段的前置阶段-在initializingBean方法里面)
  • 方法回调
    • BeanPostProcessor#postProcessBeforeInitialization

示例

public Object postProcessBeforeInitialization(Object bean, String beanName) {
    if(ObjectUtils.nullSafeEquels("userHolder", beanName) && UserHolder.class.equals(bean.getClass())) {
        // UserHolder description = "The user holder v2"
        userHolder.setDescription("The user holder v3");
    }
    return bean;
}

源码分析:

public class AbstractAutowireCapableBeanFactory {
    
    protected Object initializeBean(final  String beanName, final Object be an, @Nullable    RootBeanDefinition mbd) {
        ...
        if(mdb == null || !mdb.isSynthetic()) {
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); 
        }
    }
}

/**
 * Apply BeanPostProcessors to the given existing bean
 * instance, invoking their postProcessBeforeInitialization methods.
 * The returned bean instance may be a wrapper around the original.
 */
public Object applyBeanPostProcessorBeforeInitialization(Object existingBean, String beanName) {
    Object result = existingBean;
    // 按照顺序逐一进行操作
    for(BeanPostProcessor processor : getBeanPostProcessors()) {
        Object current = processor.postProcessBeforeInitialization(result, beanName);
        if(current == null) {
            return result;
        }
        result = current;
    }
    return result; 
}

Spring Bean初始化阶段

  • Bean初始化
    • @PostConsturct标注方法, 依赖于注解驱动,依赖于ApplicationContext
    • 实现initializingBean接口的afterPropertiesSet()方法
    • 自定义初始化方法

PostConsturct在BeforeInitialization里面执行。afterPropertiesSet和自定义初始化方法都是在初始化方法里面来进行操作.

// 依赖于注解驱动
// 当前场景:BeanFactory
@PostConstruct
public void initPostConstruct() {
    // postProcessBeforeInitialization V3 -> initpostConsturct V4
    this.description = "The user holder v4";
}

@Override
public void afterPropertiesSet() throws Exception {
    // initPostConstruct V4 -> afterProperties V5
    this.description = "The user holder V5";
}

public void init() {
    
}

Spring Bean初始化后阶段

  • 方法回调:
    • BeanPostProcessor#postProcessAfterInitialization

在postConsturct,afterPropertiesSet,自定义初始化方法后,还可以对Bean做一些操作。

public Class AbstractAutowireCapableBeanFactory {
    
    // Spring初始化,包含下面几个步骤
    protected Object initializeBean () {
        
        // 1.执行aware回调
        invokeAwareMethods(beanName, bean);
        // 2.前置操作
        applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        // 3.自定义方法
        invokeInitMethods(beanName, warppedBean, mbd);
        // 4.后置操作
        applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }
}

ApplicationContext相关的回调是通过BeanPostProcessor来执行的。(ApplciationContextAwareProcessor )

Aware回调执行完之后,还有一些于ApplicationContextAware相关的回调,是通过BeanPostProcessor来执行的,其中有个类是ApplicationContextAwareProcessor

 class ApplicationContextAwareProcessor implements BeanPostProcessor {
     
    @Override
    @Nullable
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        if(!(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware || 
            bean instanceof  ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
            bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
                return bean;
        }
    }
 }
// PostConstruct 在initDestroyAnnotationBeanPostProcessor
public Class initDestroyAnnotationBeanPostProcessor {
    
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        ...
    }
}
// ApplicationContextAware,postConstruct相关的一些回调是在 applyBeanPostProcessorsBeforeInitialization里面执行的
class AbstractAutowireCapableBeanFactory {
    protected Object initializeBean() {
         ...
         applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }
}

Spring Bean初始化完成阶段

  • 方法回调:
    • Spring 4.1+:SmartInitializingSingleton#afterSingletonsInstantiated
public interface SmartInitializingSingleton {

	/**
	 * Invoked right at the end of the singleton pre-instantiation phase,
	 * with a guarantee that all regular singleton beans have been created
	 * already. {@link ListableBeanFactory#getBeansOfType} calls within
	 * this method won't trigger accidental side effects during bootstrap.
	 * <p><b>NOTE:</b> This callback won't be triggered for singleton beans
	 * lazily initialized on demand after {@link BeanFactory} bootstrap,
	 * and not for any other bean scope either. Carefully use it for beans
	 * with the intended bootstrap semantics only.
	 */
	void afterSingletonsInstantiated();

}

SmartInitilaizingSingelton的意义在于,确保所有的Bean Definition变成Spring Bean之后,逐一地进行Singleton回调。

当任何一个对象被初始化的时候,它所依赖的对象也会被初始化,可以导致Bean的过早初始化,这些过早初始化的 Bean可能不太完整。当需要Bean完全创建好之后使用,可以实现SmartInitializingSingleton进行回调。回调发生时Bean已经完全创建好了,可以放心大胆地去操作。

Spring Bean销毁前阶段

  • 方法回调
    • DestrucationAwareBeanPostProcessor#postProcessBeforeDestrucation
public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor {

	/**
	 * Apply this BeanPostProcessor to the given bean instance before its
	 * destruction, e.g. invoking custom destruction callbacks.
	 * <p>Like DisposableBean's {@code destroy} and a custom destroy method, this
	 * callback will only apply to beans which the container fully manages the
	 * lifecycle for. This is usually the case for singletons and scoped beans.
	 */
	void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException;

	/**
	 * Determine whether the given bean instance requires destruction by this
	 * post-processor.
	 * <p>The default implementation returns {@code true}. If a pre-5 implementation
	 * of {@code DestructionAwareBeanPostProcessor} does not provide a concrete
	 * implementation of this method, Spring silently assumes {@code true} as well.
	 * @param bean the bean instance to check
	 * @return {@code true} if {@link #postProcessBeforeDestruction} is supposed to
	 * be called for this bean instance eventually, or {@code false} if not needed
	 * @since 4.3
	 */
	default boolean requiresDestruction(Object bean) {
		return true;
	}

}
public class MyDestrucationAwareBeanPostProcessor implements DestructionAwareBeanPostProcessor {
    
    @Override
    public void postProcessBeforeDestrucation(Object bean, String beanName) {
        if(ObjectUtils.nullSafeEquals("userHolder", beanName) {
            UserHolder userHolder = (UserHolder) bean;
            userHolder.setDesc("The user holder V9.");
        }
    }
}

// 添加MyDestrucationAwareBeanPostProcessor 执行销毁前回调
beanFactory.addBeanPostProcessor(new MyDestrucationAwareBeanPostProcessor());

//执行Bean销毁(容器内销毁,不代表被Java GC掉了)
beanFactory.destroyBean("userHolder", userHolder);

Spring Bean销毁阶段

  • Bean销毁
    • @PreDestroy标注方法
    • 实现DisposableBean接口的destory()方法
    • 自定义销毁方法
@PreDestory
public void preDestory() {
    this.desc = "V10";
}

@Override
public void destroy() {
    this.desc = "V11";
}

// 自定义销毁方法
public void doDestroy() {
    this.desc = "V12";
}

public class DisposableBeanAdapter {
    // 销毁是通过destroy方法来实现的
    @Override
    public void destroy() {
        if(!CollectionUtils.isEmpty(this.beanPostProcessors)) {
            for(DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
                processor.postProcessBeforeDestruction(this.bean, this.beanName); 
            }
        }
        
        ((DisposableBean) this.bean).destroy();  // 实现了DisposableBean
         
        invokeCustomDestroyMethod(this.destroyMethod);
    }
}

Spring Bean垃圾回收

  • Bean垃圾回收(GC)
    • 关闭Spring容器(应用上下文)
    • 执行GC
    • Spring Beana覆盖的finalize()方法被回调
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值