SpringBoot源码分析之Spring上下文refresh(重点)

本文详细分析了SpringBoot的refresh方法,包括prepareRefresh、postProcessBeanFactory、invokeBeanFactoryPostProcessors等步骤。重点介绍了ConfigurationClassPostProcessor如何处理@Configuration注解的类,解析bean定义并注册到Spring容器中,以及BeanPostProcessor的注册和初始化过程。此外,还涉及事件广播器的初始化和监听器的注册。
摘要由CSDN通过智能技术生成

refresh


首先来看SpringApplication#run方法中refresh()方法

private void refreshContext(ConfigurableApplicationContext context) {
		refresh(context);
		if (this.registerShutdownHook) {
			try {
				context.registerShutdownHook();
			}
			catch (AccessControlException ex) {
				// Not allowed in some environments.
			}
		}
	}
调用的是 AbstractApplicationContext中的refresh方法:
protected void refresh(ApplicationContext applicationContext) {
		Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
		((AbstractApplicationContext) applicationContext).refresh();
	} 

方法如下:

@Override
public void refresh() throws BeansException, IllegalStateException {
   synchronized (this.startupShutdownMonitor) {//refresh过程只能一个线程处理,不允许并发执行
      // 刷新前准备工作
      prepareRefresh();
      // 调用子类refreshBeanFactory()方法,获取bean factory
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
      // 创建bean Factory的通用设置,添加ApplicationContextAwareProcessor,
	  // ResourceLoader、ApplicationEventPublisher、ApplicationContext这3个接口对应的bean都设置为当前的Spring容器,注册环境bean
      prepareBeanFactory(beanFactory);
      try {
         // 子类特殊的bean factory设置
		 // GenericWebApplicationContext容器会在BeanFactory中添加ServletContextAwareProcessor用于处理ServletContextAware类型的bean初始化的时候调用setServletContext或者setServletConfig方法
         postProcessBeanFactory(beanFactory);
         // 实例化beanFactoryPostProcessor
         // 调用beanFactoryPostProcessor 这里会调用ConfigurationClassPostProcessor,解析@Configuration的类为BeanDefinition,为后面实例化作准备
         invokeBeanFactoryPostProcessors(beanFactory);
         // 注册 beanPostProcessors 包括自定义的BeanPostProcessor
		 // 在实例化Bean后处理 比如AutowiredAnnotationBeanPostProcessor(处理被@Autowired注解修饰的bean并注入)、RequiredAnnotationBeanPostProcessor(处理被@Required注解修饰的方法)
		 // 这些都是在创建Context时的reader的构造器中的AnnotationConfigUtils的registerAnnotationConfigProcessors方法中注册的
         registerBeanPostProcessors(beanFactory);
         // 初始化信息源,和国际化相关
         initMessageSource();
         // 初始化容器事件传播器
         initApplicationEventMulticaster();
         // 调用子类特殊的刷新逻辑
		 // web程序的容器AnnotationConfigEmbeddedWebApplicationContext中会调用createEmbeddedServletContainer方法去创建内置的Servlet容器。
         onRefresh();
         // 为事件传播器注册事件监听器
         registerListeners();
         // 实例化所有非懒加载单例
         finishBeanFactoryInitialization(beanFactory);
         // 初始化容器的生命周期事件处理器,并发布容器的生命周期事件
         finishRefresh();
      }
      catch (BeansException ex) {
         // ...
      }
      finally {
         // ...
      }
   }
}


prepareRefresh()方法

        @Override
	protected void prepareRefresh() {
		this.scanner.clearCache();
		super.prepareRefresh();
	}
protected void prepareRefresh() {
		// 表示在真正做refresh操作之前需要准备做的事情:

		// 设置Spring容器的启动时间,撤销关闭状态,开启活跃状态。
		this.startupDate = System.currentTimeMillis();
		this.closed.set(false);
		this.active.set(true);

		if (logger.isInfoEnabled()) {
			logger.info("Refreshing " + this);
		}

		// Initialize any placeholder property sources in the context environment
		// 初始化属性源信息,初始化占位符
		initPropertySources();

		// Validate that all properties marked as required are resolvable
		// see ConfigurablePropertyResolver#setRequiredProperties
		// 验证环境信息里一些必须存在的属性
		getEnvironment().validateRequiredProperties();

		// Allow for the collection of early ApplicationEvents,
		// to be published once the multicaster is available...
		this.earlyApplicationEvents = new LinkedHashSet<>();
}

obtainFreshBeanFactory()方法

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		// 获取刷新Spring上下文的Bean工厂
		refreshBeanFactory();
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (logger.isDebugEnabled()) {
			logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
		}
		return beanFactory;
}

此时BeanFactory中注册的BeanDefinition和Bean实例



prepareBeanFactory方法

对BeanFactory(Spring Bean容器)进行相关的设置为后续的使用做准备:

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		// Tell the internal bean factory to use the context's class loader etc.
		// 设置classloader(用于加载bean),设置表达式解析器(解析bean定义中的一些表达式),添加属性编辑注册器(注册属性编辑器)
		beanFactory.setBeanClassLoader(getClassLoader());
		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

		// Configure the bean factory with context callbacks.
		// 添加ApplicationContextAwareProcessor这个BeanPostProcessor。取消ResourceLoaderAware、ApplicationEventPublisherAware、MessageSourceAware、ApplicationContextAware、EnvironmentAware这5个接口的自动注入。
		// 因为ApplicationContextAwareProcessor把这6个接口的实现工作做了
		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
		beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
		beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
		beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
		beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

		// BeanFactory interface not registered as resolvable type in a plain factory.
		// MessageSource registered (and found for autowiring) as a bean.
		// 设置特殊的类型对应的bean。BeanFactory对应刚刚获取的BeanFactory;
		// ResourceLoader、ApplicationEventPublisher、ApplicationContext这3个接口对应的bean都设置为当前的Spring容器
		beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
		beanFactory.registerResolvableDependency(ResourceLoader.class, this);
		beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
		beanFactory.registerResolvableDependency(ApplicationContext.class, this);

		// Register early post-processor for detecting inner beans as ApplicationListeners.
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

		// Detect a LoadTimeWeaver and prepare for weaving, if found.
		if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
			// Set a temporary ClassLoader for type matching.
			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
		}

		// Register default environment beans.
		// 注入一些其它信息的bean实例,比如environment、systemProperties等
		if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
			beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
		}
		if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
			beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
		}
		if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
			beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
		}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值