Spring Bean生命周期

  • 什么是生命周期:
  • Spring Bean生命周期:

  1. 实例化Bean
  2. 设置对象属性(依赖注入)
  3. 注入Aware接口:包括哪些Aware接口
  4. BeanPostProcessor:
    postProcessBeforeInitialzation( Object bean, String beanName ),早于InitializingBean执行,前置处理
    postProcessAfterInitialzation( Object bean, String beanName ),晚于InitializationBean行,后置处理。
  5.  InitializingBean与init-method
     afterPropertiesSet()

  6. DisposableBean和destroy-method

 

主要流程

  • 实例化 Instantiation、属性赋值 Populate、初始化 Initialization、销毁 Destruction

主要逻辑都在doCreate()方法中,顺序调用以下三个方法,这三个方法与三个生命周期阶段一一对应

  • createBeanInstance() 实例化、populateBean() 属性赋值、initializeBean() 初始化
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
      throws BeanCreationException {

   // Instantiate the bean.
   BeanWrapper instanceWrapper = null;
   if (instanceWrapper == null) {
       // 实例化
      instanceWrapper = createBeanInstance(beanName, mbd, args);
   }

   // Initialize the bean instance.
   Object exposedObject = bean;
   try {
       // 属性赋值
      populateBean(beanName, mbd, instanceWrapper);
       // 初始化
      exposedObject = initializeBean(beanName, exposedObject, mbd);
   }
}
  • InstantiationAwareBeanPostProcessor

postProcessBeforeInstantiation

@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
    throws BeanCreationException {

    try {
        // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
        Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
        if (bean != null) {
            return bean;
        }
    }

    try {   
        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        if (logger.isTraceEnabled()) {
            logger.trace("Finished creating instance of bean '" + beanName + "'");
        }
        return beanInstance;
    }
}

postProcessAfterInstantiation

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {

   // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
   // state of the bean before properties are set. This can be used, for example,
   // to support styles of field injection.
   boolean continueWithPropertyPopulation = true;
    // InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation()
    // 方法作为属性赋值的前置检查条件,在属性赋值之前执行,能够影响是否进行属性赋值!
   if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      for (BeanPostProcessor bp : getBeanPostProcessors()) {
         if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
               continueWithPropertyPopulation = false;
               break;
            }
         }
      }
   }

   // 忽略后续的属性赋值操作代码
}
// 见名知意,初始化阶段调用的方法
    protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {

        // 这里调用的是Group1中的三个Bean开头的Aware
        invokeAwareMethods(beanName, bean);

        Object wrappedBean = bean;
        
        // 这里调用的是Group2中的几个Aware,
        // 而实质上这里就是前面所说的BeanPostProcessor的调用点!
        // 也就是说与Group1中的Aware不同,这里是通过BeanPostProcessor(ApplicationContextAwareProcessor)实现的。
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        // 下文即将介绍的InitializingBean调用点
        invokeInitMethods(beanName, wrappedBean, mbd);
        // BeanPostProcessor的另一个调用点
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);

        return wrappedBean;
    }

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring生命周期包括实例化、配置和销毁三个阶段。首先,实例化阶段是指创建一个Bean的实例。在Spring中,Bean的实例化可以通过使用BeanFactory或ApplicationContext来获取。其次,配置阶段是指对实例化的Bean进行配置,也就是进行IOC注入。在这个阶段,Spring会根据配置文件中的Bean的id值进行相应的配置。如果Bean实现了BeanNameAware接口,Spring还会调用它实现的setBeanName(String)方法,传递的参数就是Bean的id值。最后,销毁阶段是指当Bean不再使用时进行垃圾回收。对于Singleton模式的BeanSpring会负责管理整个生命周期;而对于Prototype模式的BeanSpring在创建好并交给使用者后就不再管理后续的生命周期。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [关于Spring Bean生命周期](https://blog.csdn.net/Apeopl/article/details/82964799)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [Springbean生命周期详解](https://blog.csdn.net/qq_64169170/article/details/123052663)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值