完整Spring Bean的生命周期源码解析

阅读本文之前,请先阅读上篇博文Spring Bean后置处理器(BeanPostProcessor及其子接口)源码分析,本文将不再介绍BeanPostProcessor相关内容。
既然源码分析,我就直奔主题了。首先是org.springframework.context.support.AbstractApplicationContext.refresh()的源码:

public void refresh() throws BeansException, IllegalStateException {
   
		synchronized (this.startupShutdownMonitor) {
   
			//准备Refresh上下文环境,比如设置当前环境active=true,初始化及校验PropertySources
			prepareRefresh();

			// 刷新并获取bean工厂
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// 准备bean工厂以供当前上下文中使用
			prepareBeanFactory(beanFactory);

			try {
   
				// 允许在上下文子类中对bean工厂进行后置处理
				postProcessBeanFactory(beanFactory);

				// 调用上下文中注册为bean的工厂后置处理器
				invokeBeanFactoryPostProcessors(beanFactory);

				// 注册Bean后置处理器
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// 初始化特定上下文子类中的其他特殊bean
				onRefresh();

				// 注册监听器
				registerListeners();

				// 实例化所有剩余的(非延迟初始化)单例.
				finishBeanFactoryInitialization(beanFactory);

				// 发布相应事件,完成刷新
				finishRefresh();
			}

			catch (BeansException ex) {
   
				if (logger.isWarnEnabled()) {
   
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}

				// 发生异常,则销毁已经实例化的bean
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}

			finally {
   
				// Reset common introspection caches in Spring's core, since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}
	}

接下来是生命周期执行顺序测试代码:

测试Bean代码(该Bean与NewsService循环依赖,为了执行循环依赖后置处理器)

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("dependencyService")
public class DependencyService implements InitializingBean, DisposableBean,BeanNameAware,BeanFactoryAware {
   
	private static final Logger _LOG = LoggerFactory.getLogger(DependencyService.class);
	@Autowired
	NewsServiceImpl newsServiceImpl;

	public  DependencyService() {
   
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值