spring bean生命周期四步

首先,明确接口的概念;

  • InitializingBean 接口是为了让 bean 在构建完毕后执行一些自定义的操作
  • BeanPostProcessor 是 spring 提供的整个容器级别的生命周期接口, 用来对容器内所有 bean 的初始化做回调
    1. BeanPostProcessor 用来实现 AOP. AOP 因为要返回 bean 的代理对象, 而 BeanPostProcessor 的 postProcessAfterInitialization 方法恰恰是在实例化后调用, 所以可以再这个方法内, 返回一个 bean 的代理对象, 从而实现 AOP
    2. AutowiredAnnotationBeanPostProcessor 是 spring 内部的一个 BeanPostProcessor, 用来自动装配 bean 上的注解字段, setter 方法调用, 和任何其他的装配方法

生命周期顺序为

  1. aware 接口
  2. BeanPostProcessor.postProcessBeforeInitialization()
  3. InitializingBean.afterPropertiesSet
  4. BeanPostProcessor.postProcessAfterInitialization()

这个顺序是 beanfactory 类里面调用的, 以 AbstractAutowireCapableBeanFactory 为例

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
            invokeAwareMethods(beanName, bean);
            return null;
        }, getAccessControlContext());
    }
    else {
        //若果Bean实现了BeanNameAware、BeanClassLoaderAware、BeanFactoryAware则初始化Bean的属性值
        invokeAwareMethods(beanName, bean);
    }

    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        //applyBeanPostProcessorsBeforeInitialization 方法内部主要是
        //用来调用后置处理器BeanPostProcessor的postProcessBeforeInitialization方法
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }

    try {
        //Bean如果继承了InitializingBean类则会调用afterPropertiesSet方法,如果设置了init-method方法,
        //则调用init-method方法,afterPropertiesSet方法在init-method方法之前调用
        invokeInitMethods(beanName, wrappedBean, mbd);
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
                (mbd != null ? mbd.getResourceDescription() : null),
                beanName, "Invocation of init method failed", ex);
    }
    if (mbd == null || !mbd.isSynthetic()) {
    //applyBeanPostProcessorsAfterInitialization 方法内部主要是,
    //用来调用后置处理器BeanPostProcessor的postProcessAfterInitialization方法
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }

    return wrappedBean;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值