爆款云主机2核4G限时秒杀,88元/年起!
查看详情

活动

天翼云最新优惠活动,涵盖免费试用,产品折扣等,助您降本增效!
热门活动
  • 618智算钜惠季 爆款云主机2核4G限时秒杀,88元/年起!
  • 免费体验DeepSeek,上天翼云息壤 NEW 新老用户均可免费体验2500万Tokens,限时两周
  • 云上钜惠 HOT 爆款云主机全场特惠,更有万元锦鲤券等你来领!
  • 算力套餐 HOT 让算力触手可及
  • 天翼云脑AOne NEW 连接、保护、办公,All-in-One!
  • 中小企业应用上云专场 产品组合下单即享折上9折起,助力企业快速上云
  • 息壤高校钜惠活动 NEW 天翼云息壤杯高校AI大赛,数款产品享受线上订购超值特惠
  • 天翼云电脑专场 HOT 移动办公新选择,爆款4核8G畅享1年3.5折起,快来抢购!
  • 天翼云奖励推广计划 加入成为云推官,推荐新用户注册下单得现金奖励
免费活动
  • 免费试用中心 HOT 多款云产品免费试用,快来开启云上之旅
  • 天翼云用户体验官 NEW 您的洞察,重塑科技边界

智算服务

打造统一的产品能力,实现算网调度、训练推理、技术架构、资源管理一体化智算服务
智算云(DeepSeek专区)
科研助手
  • 算力商城
  • 应用商城
  • 开发机
  • 并行计算
算力互联调度平台
  • 应用市场
  • 算力市场
  • 算力调度推荐
一站式智算服务平台
  • 模型广场
  • 体验中心
  • 服务接入
智算一体机
  • 智算一体机
大模型
  • DeepSeek-R1-昇腾版(671B)
  • DeepSeek-R1-英伟达版(671B)
  • DeepSeek-V3-昇腾版(671B)
  • DeepSeek-R1-Distill-Llama-70B
  • DeepSeek-R1-Distill-Qwen-32B
  • Qwen2-72B-Instruct
  • StableDiffusion-V2.1
  • TeleChat-12B

应用商城

天翼云精选行业优秀合作伙伴及千余款商品,提供一站式云上应用服务
进入甄选商城进入云市场创新解决方案
办公协同
  • WPS云文档
  • 安全邮箱
  • EMM手机管家
  • 智能商业平台
财务管理
  • 工资条
  • 税务风控云
企业应用
  • 翼信息化运维服务
  • 翼视频云归档解决方案
工业能源
  • 智慧工厂_生产流程管理解决方案
  • 智慧工地
建站工具
  • SSL证书
  • 新域名服务
网络工具
  • 翼云加速
灾备迁移
  • 云管家2.0
  • 翼备份
资源管理
  • 全栈混合云敏捷版(软件)
  • 全栈混合云敏捷版(一体机)
行业应用
  • 翼电子教室
  • 翼智慧显示一体化解决方案

合作伙伴

天翼云携手合作伙伴,共创云上生态,合作共赢
天翼云生态合作中心
  • 天翼云生态合作中心
天翼云渠道合作伙伴
  • 天翼云代理渠道合作伙伴
天翼云服务合作伙伴
  • 天翼云集成商交付能力认证
天翼云应用合作伙伴
  • 天翼云云市场合作伙伴
  • 天翼云甄选商城合作伙伴
天翼云技术合作伙伴
  • 天翼云OpenAPI中心
  • 天翼云EasyCoding平台
天翼云培训认证
  • 天翼云学堂
  • 天翼云市场商学院
天翼云合作计划
  • 云汇计划
天翼云东升计划
  • 适配中心
  • 东升计划
  • 适配互认证

开发者

开发者相关功能入口汇聚
技术社区
  • 专栏文章
  • 互动问答
  • 技术视频
资源与工具
  • OpenAPI中心
开放能力
  • EasyCoding敏捷开发平台
培训与认证
  • 天翼云学堂
  • 天翼云认证
魔乐社区
  • 魔乐社区

支持与服务

为您提供全方位支持与服务,全流程技术保障,助您轻松上云,安全无忧
文档与工具
  • 文档中心
  • 新手上云
  • 自助服务
  • OpenAPI中心
定价
  • 价格计算器
  • 定价策略
基础服务
  • 售前咨询
  • 在线支持
  • 在线支持
  • 工单服务
  • 建议与反馈
  • 用户体验官
  • 服务保障
  • 客户公告
  • 会员中心
增值服务
  • 红心服务
  • 首保服务
  • 客户支持计划
  • 专家技术服务
  • 备案管家

了解天翼云

天翼云秉承央企使命,致力于成为数字经济主力军,投身科技强国伟大事业,为用户提供安全、普惠云服务
品牌介绍
  • 关于天翼云
  • 智算云
  • 天翼云4.0
  • 新闻资讯
  • 天翼云APP
基础设施
  • 全球基础设施
  • 信任中心
最佳实践
  • 精选案例
  • 超级探访
  • 云杂志
  • 分析师和白皮书
  • 天翼云·创新直播间
市场活动
  • 2025智能云生态大会
  • 2024智算云生态大会
  • 2023云生态大会
  • 2022云生态大会
  • 天翼云中国行
天翼云
  • 活动
  • 智算服务
  • 产品
  • 解决方案
  • 应用商城
  • 合作伙伴
  • 开发者
  • 支持与服务
  • 了解天翼云
      • 文档
      • 控制中心
      • 备案
      • 管理中心

      Spring Boot Application的启动过程 - 加载应用上下文

      首页 知识中心 软件开发 文章详情页

      Spring Boot Application的启动过程 - 加载应用上下文

      2025-03-25 08:08:18 阅读次数:8

      Bean,org

      背景

      1. 应用基于spring-boot-starter-web起步依赖,使用默认tomcat内置应用服务器。
      2. 应用依赖的版本:Spring Boot (2.1.5.RELEASE),Spring (5.1.7.RELEASE)。
      3. 本文对Spring Boot Application启动过程中的核心方法进行了梳理,以帮助大家了解Spring Boot应用启动的大致过程。
      4. 本文只是粘贴了相关代码,并未对每个方法进行深入分析。

      注意区分 BeanDefinition Instantiation Initializtion

      1. Spring ApplicationContext核心类图

      • 接口浅蓝色
      • ApplicationContext相关类为绿色
      • BeanFactory相关接口为深蓝色
        Spring Boot Application的启动过程 - 加载应用上下文

      2. Spring Boot Application启动过程中的核心步骤

      1. org.springframework.boot.SpringApplication#run(java.lang.String…)
      2. org.springframework.context.support.AbstractApplicationContext#refresh
      3. org.springframework.context.support.AbstractApplicationContext#prepareBeanFactory
      4. org.springframework.context.support.AbstractApplicationContext#invokeBeanFactoryPostProcessors
      5. org.springframework.context.support.AbstractApplicationContext#registerBeanPostProcessors
      6. org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#onRefresh
      7. org.springframework.context.support.AbstractApplicationContext#finishBeanFactoryInitialization
      8. org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons
      9. org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
      10. org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])
      11. org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
      12. org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean
      13. org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition)

      3. 应用启动类:SpringApplication#run

      这段代码包含了Spring Boot应用启动的主流程,其中在流程的关键环节会触发应用事件,所有的关键事件在代码中都添加了注释。

      /**
       * Run the Spring application, creating and refreshing a new
       * {@link ApplicationContext}.
       * @param args the application arguments (usually passed from a Java main method)
       * @return a running {@link ApplicationContext}
       */
      public ConfigurableApplicationContext run(String... args) {
      	StopWatch stopWatch = new StopWatch();
      	stopWatch.start();
      	ConfigurableApplicationContext context = null;
      	Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
      	configureHeadlessProperty();
      	SpringApplicationRunListeners listeners = getRunListeners(args);
      	// 1. starting event
      	listeners.starting();
      	try {
      		ApplicationArguments applicationArguments = new DefaultApplicationArguments(
      				args);
      		// 2. environment prepared event
      		ConfigurableEnvironment environment = prepareEnvironment(listeners,
      				applicationArguments);
      		configureIgnoreBeanInfo(environment);
      		Banner printedBanner = printBanner(environment);
      		context = createApplicationContext();
      		exceptionReporters = getSpringFactoriesInstances(
      				SpringBootExceptionReporter.class,
      				new Class[] { ConfigurableApplicationContext.class }, context);
      		// 3. applyInitializers : org.springframework.context.ApplicationContextInitializer
      		// 4. context prepared event & 5. context loaded event
      		prepareContext(context, environment, listeners, applicationArguments,
      				printedBanner);
      		// multicast event org.springframework.context.event.ContextRefreshedEvent when refresh finished.
      		refreshContext(context);
      		afterRefresh(context, applicationArguments);
      		stopWatch.stop();
      		if (this.logStartupInfo) {
      			new StartupInfoLogger(this.mainApplicationClass)
      					.logStarted(getApplicationLog(), stopWatch);
      		}
      		// 6. application started event
      		listeners.started(context);
      		callRunners(context, applicationArguments);
      	}
      	catch (Throwable ex) {
      		// 7. start failured event
      		handleRunFailure(context, ex, exceptionReporters, listeners);
      		throw new IllegalStateException(ex);
      	}
      
      	try {
      		// 8. running event
      		listeners.running(context);
      	}
      	catch (Throwable ex) {
      		handleRunFailure(context, ex, exceptionReporters, null);
      		throw new IllegalStateException(ex);
      	}
      	return context;
      }
      

      4. 核心逻辑:更新应用上下文(AbstractApplicationContext#refresh)

      应用启动的一个重要环节就是应用上下文(Application Context)的启动,下面的代码包含了其核心逻辑。

      注意以下两个接口的区别:
      org.springframework.beans.factory.config.BeanPostProcessor
      org.springframework.beans.factory.config.BeanFactoryPostProcessor

      @Override
      public void refresh() throws BeansException, IllegalStateException {
      	synchronized (this.startupShutdownMonitor) {
      		// Prepare this context for refreshing.
      		prepareRefresh();
      
      		// Tell the subclass to refresh the internal bean factory.
      		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
      
      		// Prepare the bean factory for use in this context.
      		prepareBeanFactory(beanFactory);
      
      		try {
      			// Allows post-processing of the bean factory in context subclasses.
      			postProcessBeanFactory(beanFactory);
      
      			// Invoke factory processors registered as beans in the context.
      			invokeBeanFactoryPostProcessors(beanFactory);
      
      			// Register bean processors that intercept bean creation.
      			registerBeanPostProcessors(beanFactory);
      
      			// Initialize message source for this context.
      			initMessageSource();
      
      			// Initialize event multicaster for this context.
      			initApplicationEventMulticaster();
      
      			// Initialize other special beans in specific context subclasses.
      			onRefresh();
      
      			// Check for listener beans and register them.
      			registerListeners();
      
      			// 实例化所有剩余的(非惰性初始化)单例
      			// Instantiate all remaining (non-lazy-init) singletons.
      			finishBeanFactoryInitialization(beanFactory);
      
      			// Last step: publish corresponding event.
      			finishRefresh();
      		}
      
      		catch (BeansException ex) {
      			if (logger.isWarnEnabled()) {
      				logger.warn("Exception encountered during context initialization - " +
      						"cancelling refresh attempt: " + ex);
      			}
      
      			// Destroy already created singletons to avoid dangling resources.
      			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();
      		}
      	}
      }
      

      4.1 准备BeanFactory:AbstractApplicationContext#prepareBeanFactory

      重点关注 ApplicationContextAwareProcessor 类,这个一个 BeanPostProcessor,所有实现了 EnvironmentAware,EmbeddedValueResolverAware, ResourceLoaderAware, ApplicationEventPublisherAware, MessageSourceAware,ApplicationContextAware 接口的Bean,都是通过这个类进行设值的。

      关注 ApplicationListenerDetector 类,该类将所有实现 ApplicationListener 接口的 Bean 注册为 ApplicationContext 的事件监听器。
      如果要监听 ApplicationContext 的事件,只需要实现 org.springframework.context.ApplicationListener 接口添加事件处理逻辑,并注册 Bean即可。

      可参考 org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor 实现。

      org.springframework.context.support.AbstractApplicationContext#prepareBeanFactory

      /**
       * Configure the factory's standard context characteristics,
       * such as the context's ClassLoader and post-processors.
       * @param beanFactory the BeanFactory to configure
       */
      protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
      	// Tell the internal bean factory to use the context's class loader etc.
      	beanFactory.setBeanClassLoader(getClassLoader());
      	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
      	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
      
      	// Configure the bean factory with context callbacks.
      	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.
      	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.
      	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());
      	}
      }
      

      4.2 调用BeanFactoryPostProcessor

      调用所有注册的BeanFactoryPostProcessor。该过程主要是加载基于自动配置方式注册的Bean Definition,核心类ConfigurationClassPostProcessor。可参考[SBIA-18] - ConfigurationClassPostProcessor 的处理逻辑 - 基于注解的 bean 定义加载过程。

      可以通过BeanDefinitionRegistryPostProcessor或ImportBeanDefinitionRegistrar方式注册自定义Bean。可参考[SBIA-19] - 如何动态添加 Bean Definition。

      org.springframework.context.support.AbstractApplicationContext#invokeBeanFactoryPostProcessors

      /**
      	 * Instantiate and invoke all registered BeanFactoryPostProcessor beans,
      	 * respecting explicit order if given.
      	 * <p>Must be called before singleton instantiation.
      	 */
      	protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
      		PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
      
      		// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
      		// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
      		if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
      			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
      			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
      		}
      	}
      

      4.3 注册BeanPostProcessor

      从 BeanFactory 中查找所有类型为 BeanPostProcessor 的 bean definition,实例化并注册 bean。其注册优先级按类型 PriorityOrdered > Ordered > the rest. 且MergedBeanDefinitionPostProcessor的优先级低于其他 processor 的优先级。

      其逻辑通过代理类PostProcessorRegistrationDelegate实现,org.springframework.context.support.PostProcessorRegistrationDelegate#registerBeanPostProcessors

      public static void registerBeanPostProcessors(
      		ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
      
      	String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
      
      	// Register BeanPostProcessorChecker that logs an info message when
      	// a bean is created during BeanPostProcessor instantiation, i.e. when
      	// a bean is not eligible for getting processed by all BeanPostProcessors.
      	int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
      	beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
      
      	// Separate between BeanPostProcessors that implement PriorityOrdered,
      	// Ordered, and the rest.
      	List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
      	List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
      	List<String> orderedPostProcessorNames = new ArrayList<>();
      	List<String> nonOrderedPostProcessorNames = new ArrayList<>();
      	for (String ppName : postProcessorNames) {
      		if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
      			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
      			priorityOrderedPostProcessors.add(pp);
      			if (pp instanceof MergedBeanDefinitionPostProcessor) {
      				internalPostProcessors.add(pp);
      			}
      		}
      		else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
      			orderedPostProcessorNames.add(ppName);
      		}
      		else {
      			nonOrderedPostProcessorNames.add(ppName);
      		}
      	}
      
      	// First, register the BeanPostProcessors that implement PriorityOrdered.
      	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
      	registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
      
      	// Next, register the BeanPostProcessors that implement Ordered.
      	List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
      	for (String ppName : orderedPostProcessorNames) {
      		BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
      		orderedPostProcessors.add(pp);
      		if (pp instanceof MergedBeanDefinitionPostProcessor) {
      			internalPostProcessors.add(pp);
      		}
      	}
      	sortPostProcessors(orderedPostProcessors, beanFactory);
      	registerBeanPostProcessors(beanFactory, orderedPostProcessors);
      
      	// Now, register all regular BeanPostProcessors.
      	List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
      	for (String ppName : nonOrderedPostProcessorNames) {
      		BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
      		nonOrderedPostProcessors.add(pp);
      		if (pp instanceof MergedBeanDefinitionPostProcessor) {
      			internalPostProcessors.add(pp);
      		}
      	}
      	registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
      
      	// Finally, re-register all internal BeanPostProcessors.
      	sortPostProcessors(internalPostProcessors, beanFactory);
      	registerBeanPostProcessors(beanFactory, internalPostProcessors);
      
      	// Re-register post-processor for detecting inner beans as ApplicationListeners,
      	// moving it to the end of the processor chain (for picking up proxies etc).
      	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
      }
      

      4.4 加载WEB专属Bean:ServletWebServerApplicationContext#onRefresh

      ServletWebServerApplicationContext是AbstractApplicationContext的子类,它增加了嵌入式Web服务器相关的Bean。

      @Override
      protected void onRefresh() {
      	super.onRefresh();
      	try {
      		createWebServer();
      	}
      	catch (Throwable ex) {
      		throw new ApplicationContextException("Unable to start web server", ex);
      	}
      }
      

      4.5 实例化非懒加载单例Bean:AbstractApplicationContext#finishBeanFactoryInitialization

      实例化所有剩余的单例Bean。

      /**
       * Finish the initialization of this context's bean factory,
       * initializing all remaining singleton beans.
       */
      protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
      	// Initialize conversion service for this context.
      	if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
      			beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
      		beanFactory.setConversionService(
      				beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
      	}
      
      	// Register a default embedded value resolver if no bean post-processor
      	// (such as a PropertyPlaceholderConfigurer bean) registered any before:
      	// at this point, primarily for resolution in annotation attribute values.
      	if (!beanFactory.hasEmbeddedValueResolver()) {
      		beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
      	}
      
      	// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
      	String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
      	for (String weaverAwareName : weaverAwareNames) {
      		getBean(weaverAwareName);
      	}
      
      	// Stop using the temporary ClassLoader for type matching.
      	beanFactory.setTempClassLoader(null);
      
      	// Allow for caching all bean definition metadata, not expecting further changes.
      	beanFactory.freezeConfiguration();
      
      	// Instantiate all remaining (non-lazy-init) singletons.
      	beanFactory.preInstantiateSingletons();
      }
      

      4.5.1 预实例化单例Bean: DefaultListableBeanFactory#preInstantiateSingletons

      主要逻辑:

      • 实例化所有的单例Bean。
      • 遍历所以实例化的单例Bean,如果Bean是SmartInitializingSingleton的实例,那么执行org.springframework.beans.factory.**SmartInitializingSingleton#afterSingletonsInstantiated()**方法
      @Override
      public void preInstantiateSingletons() throws BeansException {
      	if (logger.isTraceEnabled()) {
      		logger.trace("Pre-instantiating singletons in " + this);
      	}
      
      	// Iterate over a copy to allow for init methods which in turn register new bean definitions.
      	// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
      	List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
      
      	// Trigger initialization of all non-lazy singleton beans...
      	for (String beanName : beanNames) {
      		RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
      		if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
      			// factory bean
      			if (isFactoryBean(beanName)) {
      				Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
      				if (bean instanceof FactoryBean) {
      					final FactoryBean<?> factory = (FactoryBean<?>) bean;
      					boolean isEagerInit;
      					if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
      						isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
      										((SmartFactoryBean<?>) factory)::isEagerInit,
      								getAccessControlContext());
      					}
      					else {
      						isEagerInit = (factory instanceof SmartFactoryBean &&
      								((SmartFactoryBean<?>) factory).isEagerInit());
      					}
      					if (isEagerInit) {
      						getBean(beanName);
      					}
      				}
      			}
      			// non factory bean
      			else {
      				getBean(beanName);
      			}
      		}
      	}
      
      	// Trigger post-initialization callback for all applicable beans...
      	for (String beanName : beanNames) {
      		Object singletonInstance = getSingleton(beanName);
      		if (singletonInstance instanceof SmartInitializingSingleton) {
      			final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
      			if (System.getSecurityManager() != null) {
      				AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
      					smartSingleton.afterSingletonsInstantiated();
      					return null;
      				}, getAccessControlContext());
      			}
      			else {
      				smartSingleton.afterSingletonsInstantiated();
      			}
      		}
      	}
      }
      

      4.5.2 获取Bean:AbstractBeanFactory#doGetBean

      大致逻辑:

      • 如果缓存中存在,从缓存中获取
      • 缓存中不存在
        • 如果当前bean正在创建中,抛异常
        • 查询在Bean Factory中是否存在Bean Definition
        • 如果当前Bean Factory中不存在Bean Definition,从父Bean Factory中获取Bean,并返回
        • 如果当前Bean Factory中存在Bean Definition
          • 获取Bean Definition
          • 确保当前Bean的依赖Bean完成初始化
          • 实例化Bean
          • 确保当前Bean实例的类型与需求类型符合
          • 返回Bean实例
      /**
       * Return an instance, which may be shared or independent, of the specified bean.
       * @param name the name of the bean to retrieve
       * @param requiredType the required type of the bean to retrieve
       * @param args arguments to use when creating a bean instance using explicit arguments
       * (only applied when creating a new instance as opposed to retrieving an existing one)
       * @param typeCheckOnly whether the instance is obtained for a type check,
       * not for actual use
       * @return an instance of the bean
       * @throws BeansException if the bean could not be created
       */
      @SuppressWarnings("unchecked")
      protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
      		@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
      
      	final String beanName = transformedBeanName(name);
      	Object bean;
      
      	// Eagerly check singleton cache for manually registered singletons.
      	Object sharedInstance = getSingleton(beanName);
      	if (sharedInstance != null && args == null) {
      		if (logger.isTraceEnabled()) {
      			if (isSingletonCurrentlyInCreation(beanName)) {
      				logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
      						"' that is not fully initialized yet - a consequence of a circular reference");
      			}
      			else {
      				logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
      			}
      		}
      		bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
      	}
      
      	else {
      		// Fail if we're already creating this bean instance:
      		// We're assumably within a circular reference.
      		if (isPrototypeCurrentlyInCreation(beanName)) {
      			throw new BeanCurrentlyInCreationException(beanName);
      		}
      
      		// Check if bean definition exists in this factory.
      		BeanFactory parentBeanFactory = getParentBeanFactory();
      		if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
      			// Not found -> check parent.
      			String nameToLookup = originalBeanName(name);
      			if (parentBeanFactory instanceof AbstractBeanFactory) {
      				return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
      						nameToLookup, requiredType, args, typeCheckOnly);
      			}
      			else if (args != null) {
      				// Delegation to parent with explicit args.
      				return (T) parentBeanFactory.getBean(nameToLookup, args);
      			}
      			else if (requiredType != null) {
      				// No args -> delegate to standard getBean method.
      				return parentBeanFactory.getBean(nameToLookup, requiredType);
      			}
      			else {
      				return (T) parentBeanFactory.getBean(nameToLookup);
      			}
      		}
      
      		if (!typeCheckOnly) {
      			markBeanAsCreated(beanName);
      		}
      
      		try {
      			final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
      			checkMergedBeanDefinition(mbd, beanName, args);
      
      			// Guarantee initialization of beans that the current bean depends on.
      			String[] dependsOn = mbd.getDependsOn();
      			if (dependsOn != null) {
      				for (String dep : dependsOn) {
      					if (isDependent(beanName, dep)) {
      						throw new BeanCreationException(mbd.getResourceDescription(), beanName,
      								"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
      					}
      					registerDependentBean(dep, beanName);
      					try {
      						getBean(dep);
      					}
      					catch (NoSuchBeanDefinitionException ex) {
      						throw new BeanCreationException(mbd.getResourceDescription(), beanName,
      								"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
      					}
      				}
      			}
      
      			// Create bean instance.
      			if (mbd.isSingleton()) {
      				sharedInstance = getSingleton(beanName, () -> {
      					try {
      						return createBean(beanName, mbd, args);
      					}
      					catch (BeansException ex) {
      						// Explicitly remove instance from singleton cache: It might have been put there
      						// eagerly by the creation process, to allow for circular reference resolution.
      						// Also remove any beans that received a temporary reference to the bean.
      						destroySingleton(beanName);
      						throw ex;
      					}
      				});
      				bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
      			}
      
      			else if (mbd.isPrototype()) {
      				// It's a prototype -> create a new instance.
      				Object prototypeInstance = null;
      				try {
      					beforePrototypeCreation(beanName);
      					prototypeInstance = createBean(beanName, mbd, args);
      				}
      				finally {
      					afterPrototypeCreation(beanName);
      				}
      				bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
      			}
      
      			else {
      				String scopeName = mbd.getScope();
      				final Scope scope = this.scopes.get(scopeName);
      				if (scope == null) {
      					throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
      				}
      				try {
      					Object scopedInstance = scope.get(beanName, () -> {
      						beforePrototypeCreation(beanName);
      						try {
      							return createBean(beanName, mbd, args);
      						}
      						finally {
      							afterPrototypeCreation(beanName);
      						}
      					});
      					bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
      				}
      				catch (IllegalStateException ex) {
      					throw new BeanCreationException(beanName,
      							"Scope '" + scopeName + "' is not active for the current thread; consider " +
      							"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
      							ex);
      				}
      			}
      		}
      		catch (BeansException ex) {
      			cleanupAfterBeanCreationFailure(beanName);
      			throw ex;
      		}
      	}
      
      	// Check if required type matches the type of the actual bean instance.
      	if (requiredType != null && !requiredType.isInstance(bean)) {
      		try {
      			T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
      			if (convertedBean == null) {
      				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
      			}
      			return convertedBean;
      		}
      		catch (TypeMismatchException ex) {
      			if (logger.isTraceEnabled()) {
      				logger.trace("Failed to convert bean '" + name + "' to required type '" +
      						ClassUtils.getQualifiedName(requiredType) + "'", ex);
      			}
      			throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
      		}
      	}
      	return (T) bean;
      }
      

      4.5.3 创建Bean:AbstractAutowireCapableBeanFactory#createBean

      在调用真正的创建Bean逻辑前,允许通过InstantiationAwareBeanPostProcessor返回目标Bean实例的代理。

      org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation
      org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization

      如果不生成代理,则创建普通bean。

      /**
       * Central method of this class: creates a bean instance,
       * populates the bean instance, applies post-processors, etc.
       * @see #doCreateBean
       */
      @Override
      protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
      		throws BeanCreationException {
      
      	if (logger.isTraceEnabled()) {
      		logger.trace("Creating instance of bean '" + beanName + "'");
      	}
      	RootBeanDefinition mbdToUse = mbd;
      
      	// Make sure bean class is actually resolved at this point, and
      	// clone the bean definition in case of a dynamically resolved Class
      	// which cannot be stored in the shared merged bean definition.
      	Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
      	if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
      		mbdToUse = new RootBeanDefinition(mbd);
      		mbdToUse.setBeanClass(resolvedClass);
      	}
      
      	// Prepare method overrides.
      	try {
      		mbdToUse.prepareMethodOverrides();
      	}
      	catch (BeanDefinitionValidationException ex) {
      		throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
      				beanName, "Validation of method overrides failed", ex);
      	}
      
      	try {
      		// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
      		// org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation
      		// org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization
      		Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
      		if (bean != null) {
      			return bean;
      		}
      	}
      	catch (Throwable ex) {
      		throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
      				"BeanPostProcessor before instantiation of bean failed", ex);
      	}
      
      	try {
      		Object beanInstance = doCreateBean(beanName, mbdToUse, args);
      		if (logger.isTraceEnabled()) {
      			logger.trace("Finished creating instance of bean '" + beanName + "'");
      		}
      		return beanInstance;
      	}
      	catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
      		// A previously detected exception with proper bean creation context already,
      		// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
      		throw ex;
      	}
      	catch (Throwable ex) {
      		throw new BeanCreationException(
      				mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
      	}
      }
      
      4.5.3.1 创建Bean实例:AbstractAutowireCapableBeanFactory#doCreateBean

      创建Bean实例的主要逻辑:

      • 实例化Bean
      • 通过org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition改变 BeanDefinition 的属性配置
      • 设置Bean属性
      • 初始化Bean
      • 标记一次性Bean
      /**
       * Actually create the specified bean. Pre-creation processing has already happened
       * at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
       * <p>Differentiates between default bean instantiation, use of a
       * factory method, and autowiring a constructor.
       * @param beanName the name of the bean
       * @param mbd the merged bean definition for the bean
       * @param args explicit arguments to use for constructor or factory method invocation
       * @return a new instance of the bean
       * @throws BeanCreationException if the bean could not be created
       * @see #instantiateBean
       * @see #instantiateUsingFactoryMethod
       * @see #autowireConstructor
       */
      protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
      		throws BeanCreationException {
      
      	// Instantiate the bean.
      	BeanWrapper instanceWrapper = null;
      	if (mbd.isSingleton()) {
      		instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
      	}
      	if (instanceWrapper == null) {
      		instanceWrapper = createBeanInstance(beanName, mbd, args);
      	}
      	final Object bean = instanceWrapper.getWrappedInstance();
      	Class<?> beanType = instanceWrapper.getWrappedClass();
      	if (beanType != NullBean.class) {
      		mbd.resolvedTargetType = beanType;
      	}
      
      	// Allow post-processors to modify the merged bean definition.
      	synchronized (mbd.postProcessingLock) {
      		if (!mbd.postProcessed) {
      			try {
      				// org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
      				applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
      			}
      			catch (Throwable ex) {
      				throw new BeanCreationException(mbd.getResourceDescription(), beanName,
      						"Post-processing of merged bean definition failed", ex);
      			}
      			mbd.postProcessed = true;
      		}
      	}
      
      	// Eagerly cache singletons to be able to resolve circular references
      	// even when triggered by lifecycle interfaces like BeanFactoryAware.
      	boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
      			isSingletonCurrentlyInCreation(beanName));
      	if (earlySingletonExposure) {
      		if (logger.isTraceEnabled()) {
      			logger.trace("Eagerly caching bean '" + beanName +
      					"' to allow for resolving potential circular references");
      		}
      		addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
      	}
      
      	// Initialize the bean instance.
      	Object exposedObject = bean;
      	try {
      		populateBean(beanName, mbd, instanceWrapper);
      		exposedObject = initializeBean(beanName, exposedObject, mbd);
      	}
      	catch (Throwable ex) {
      		if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
      			throw (BeanCreationException) ex;
      		}
      		else {
      			throw new BeanCreationException(
      					mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
      		}
      	}
      
      	if (earlySingletonExposure) {
      		Object earlySingletonReference = getSingleton(beanName, false);
      		if (earlySingletonReference != null) {
      			if (exposedObject == bean) {
      				exposedObject = earlySingletonReference;
      			}
      			else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
      				String[] dependentBeans = getDependentBeans(beanName);
      				Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
      				for (String dependentBean : dependentBeans) {
      					if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
      						actualDependentBeans.add(dependentBean);
      					}
      				}
      				if (!actualDependentBeans.isEmpty()) {
      					throw new BeanCurrentlyInCreationException(beanName,
      							"Bean with name '" + beanName + "' has been injected into other beans [" +
      							StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
      							"] in its raw version as part of a circular reference, but has eventually been " +
      							"wrapped. This means that said other beans do not use the final version of the " +
      							"bean. This is often the result of over-eager type matching - consider using " +
      							"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
      				}
      			}
      		}
      	}
      
      	// Register bean as disposable.
      	try {
      		registerDisposableBeanIfNecessary(beanName, bean, mbd);
      	}
      	catch (BeanDefinitionValidationException ex) {
      		throw new BeanCreationException(
      				mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
      	}
      
      	return exposedObject;
      }
      
      4.5.3.2 设置Bean属性:AbstractAutowireCapableBeanFactory#populateBean

      设置Bean实例属性的主要逻辑:

      • 设置属性前,调用org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation改变Bean实例的状态。
      • 设置属性值,支持AUTOWIRE_BY_NAME & AUTOWIRE_BY_TYPE
      • 设置属性后,调用org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessProperties。
      /**
       * Populate the bean instance in the given BeanWrapper with the property values
       * from the bean definition.
       * @param beanName the name of the bean
       * @param mbd the bean definition for the bean
       * @param bw the BeanWrapper with bean instance
       */
      @SuppressWarnings("deprecation")  // for postProcessPropertyValues
      protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
      	if (bw == null) {
      		if (mbd.hasPropertyValues()) {
      			throw new BeanCreationException(
      					mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
      		}
      		else {
      			// Skip property population phase for null instance.
      			return;
      		}
      	}
      
      	// 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;
      
      	if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      		for (BeanPostProcessor bp : getBeanPostProcessors()) {
      			if (bp instanceof InstantiationAwareBeanPostProcessor) {
      				InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
      				// org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation
      				if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
      					continueWithPropertyPopulation = false;
      					break;
      				}
      			}
      		}
      	}
      
      	if (!continueWithPropertyPopulation) {
      		return;
      	}
      
      	PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
      
      	if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
      		MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
      		// Add property values based on autowire by name if applicable.
      		if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
      			autowireByName(beanName, mbd, bw, newPvs);
      		}
      		// Add property values based on autowire by type if applicable.
      		if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
      			autowireByType(beanName, mbd, bw, newPvs);
      		}
      		pvs = newPvs;
      	}
      
      	boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
      	boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
      
      	PropertyDescriptor[] filteredPds = null;
      	if (hasInstAwareBpps) {
      		if (pvs == null) {
      			pvs = mbd.getPropertyValues();
      		}
      		for (BeanPostProcessor bp : getBeanPostProcessors()) {
      			if (bp instanceof InstantiationAwareBeanPostProcessor) {
      				InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
      				// org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessProperties
      				PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
      				if (pvsToUse == null) {
      					if (filteredPds == null) {
      						filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
      					}
      					pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
      					if (pvsToUse == null) {
      						return;
      					}
      				}
      				pvs = pvsToUse;
      			}
      		}
      	}
      	if (needsDepCheck) {
      		if (filteredPds == null) {
      			filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
      		}
      		checkDependencies(beanName, mbd, filteredPds, pvs);
      	}
      
      	if (pvs != null) {
      		applyPropertyValues(beanName, mbd, bw, pvs);
      	}
      }
      
      4.5.3.3 初始化Bean: AbstractAutowireCapableBeanFactory#initializeBean

      初始化Bean的主要逻辑:

      • 调用Aware方法:BeanNameAware,BeanClassLoaderAware,BeanFactoryAware
      • 调用org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization
      • 如果实现了InitializingBean接口,调用Bean的org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
      • 如果设置了init-method,则调用设置的初始化方法
      • 调用org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization
      /**
       * Initialize the given bean instance, applying factory callbacks
       * as well as init methods and bean post processors.
       * <p>Called from {@link #createBean} for traditionally defined beans,
       * and from {@link #initializeBean} for existing bean instances.
       * @param beanName the bean name in the factory (for debugging purposes)
       * @param bean the new bean instance we may need to initialize
       * @param mbd the bean definition that the bean was created with
       * (can also be {@code null}, if given an existing bean instance)
       * @return the initialized bean instance (potentially wrapped)
       * @see BeanNameAware
       * @see BeanClassLoaderAware
       * @see BeanFactoryAware
       * @see #applyBeanPostProcessorsBeforeInitialization
       * @see #invokeInitMethods
       * @see #applyBeanPostProcessorsAfterInitialization
       */
      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 {
      		invokeAwareMethods(beanName, bean);
      	}
      
      	Object wrappedBean = bean;
      	if (mbd == null || !mbd.isSynthetic()) {
      		// org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization
      		wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
      	}
      
      	try {
      		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()) {
      		wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
      	}
      
      	return wrappedBean;
      }
      
      private void invokeAwareMethods(final String beanName, final Object bean) {
      	if (bean instanceof Aware) {
      		if (bean instanceof BeanNameAware) {
      			((BeanNameAware) bean).setBeanName(beanName);
      		}
      		if (bean instanceof BeanClassLoaderAware) {
      			ClassLoader bcl = getBeanClassLoader();
      			if (bcl != null) {
      				((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
      			}
      		}
      		if (bean instanceof BeanFactoryAware) {
      			((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
      		}
      	}
      }
      
      /**
       * Give a bean a chance to react now all its properties are set,
       * and a chance to know about its owning bean factory (this object).
       * This means checking whether the bean implements InitializingBean or defines
       * a custom init method, and invoking the necessary callback(s) if it does.
       * @param beanName the bean name in the factory (for debugging purposes)
       * @param bean the new bean instance we may need to initialize
       * @param mbd the merged bean definition that the bean was created with
       * (can also be {@code null}, if given an existing bean instance)
       * @throws Throwable if thrown by init methods or by the invocation process
       * @see #invokeCustomInitMethod
       */
      protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
      		throws Throwable {
      
      	boolean isInitializingBean = (bean instanceof InitializingBean);
      	if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
      		if (logger.isTraceEnabled()) {
      			logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
      		}
      		if (System.getSecurityManager() != null) {
      			try {
      				AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
      					((InitializingBean) bean).afterPropertiesSet();
      					return null;
      				}, getAccessControlContext());
      			}
      			catch (PrivilegedActionException pae) {
      				throw pae.getException();
      			}
      		}
      		else {
      			((InitializingBean) bean).afterPropertiesSet();
      		}
      	}
      
      	if (mbd != null && bean.getClass() != NullBean.class) {
      		String initMethodName = mbd.getInitMethodName();
      		if (StringUtils.hasLength(initMethodName) &&
      				!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
      				!mbd.isExternallyManagedInitMethod(initMethodName)) {
      			invokeCustomInitMethod(beanName, bean, mbd);
      		}
      	}
      }
      

      4.6 Finish the refresh of this context

      一些实现了Lifecycle接口的Bean会在这个阶段执行。如启动WebSocket相关的LifeCycle Bean等就是在这个阶段启动的。包括:
      org.springframework.web.socket.server.support.WebSocketHandlerMapping
      org.springframework.web.socket.server.support.WebSocketHttpRequestHandler
      org.springframework.web.socket.sockjs.support.SockJsHttpRequestHandler
      等。

      /**
      	 * Finish the refresh of this context, invoking the LifecycleProcessor's
      	 * onRefresh() method and publishing the
      	 * {@link org.springframework.context.event.ContextRefreshedEvent}.
      	 */
      	protected void finishRefresh() {
      		// Clear context-level resource caches (such as ASM metadata from scanning).
      		clearResourceCaches();
      
      		// Initialize lifecycle processor for this context.
      		initLifecycleProcessor();
      
      		// Propagate refresh to lifecycle processor first.
      		getLifecycleProcessor().onRefresh();
      
      		// Publish the final event.
      		publishEvent(new ContextRefreshedEvent(this));
      
      		// Participate in LiveBeansView MBean, if active.
      		LiveBeansView.registerApplicationContext(this);
      	}
      

      附录

      1. ApplicationEvent触发顺序

      ApplicationEvent触发顺序(包括应用事件和容器事件):

      1. org.springframework.boot.context.event.ApplicationStartingEvent
      2. org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent
      3. org.springframework.boot.context.event.ApplicationContextInitializedEvent
      4. org.springframework.boot.context.event.ApplicationPreparedEvent
      5. org.springframework.context.event.ContextRefreshedEvent
      6. org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent
      7. org.springframework.boot.context.event.ApplicationStartedEvent
      8. org.springframework.boot.context.event.ApplicationReadyEvent
      版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://blog.csdn.net/ttyy1112/article/details/90403513,作者:阿湯哥,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。

      上一篇:【C++二分查找 贪心】792. 匹配子序列的单词数|1695

      下一篇:软件开发中的几点实用经验分享

      相关文章

      2025-05-12 10:19:12

      SpringBoot学习(6)(Bean对象扫描)(@ComponentScan)

      SpringBoot学习(6)(Bean对象扫描)(@ComponentScan)

      2025-05-12 10:19:12
      Bean , springboot , 启动 , 扫描 , 注解
      2025-05-08 09:03:07

      spring Bean的作用域和生命周期

      spring Bean的作用域和生命周期

      2025-05-08 09:03:07
      Bean , method , spring , 作用域 , 配置文件
      2025-05-06 09:19:12

      Spring的 Aop的完整实现流程?

      Spring的 Aop的完整实现流程?

      2025-05-06 09:19:12
      AOP , Bean
      2025-04-22 09:40:08

      【ETL工具】kettle 程序报错 Javascript error: TypeError: Cannot call method “trim“ of null

      【ETL工具】kettle 程序报错 Javascript error: TypeError: Cannot call method “trim“ of null

      2025-04-22 09:40:08
      java , javascript , org
      2025-04-18 07:09:19

      深入理解Spring中的Bean循环依赖与解决机制

      Bean循环依赖是指两个或多个Bean之间相互依赖,形成依赖闭环的情况。例如,Bean A依赖Bean B,而Bean B又依赖Bean A。这种情况下,如果没有特殊处理,容器将无法正确初始化这些Bean,从而导致应用启动失败。

      2025-04-18 07:09:19
      Bean , Spring , 依赖 , 初始化 , 循环 , 缓存 , 解决
      2025-04-11 07:11:40

      java使用poi解密excel文件

      java使用poi解密excel文件

      2025-04-11 07:11:40
      apache , import , org , poi , 解密
      2025-04-09 09:15:47

      java使用poi实现excel保护工作表实例代码(支持.xls和.xlsx)

      java使用poi实现excel保护工作表实例代码(支持.xls和.xlsx)

      2025-04-09 09:15:47
      apache , import , java , org , poi , test
      2025-04-01 10:16:07

      深入解析 Spring Bean 的生命周期

      深入解析 Spring Bean 的生命周期

      2025-04-01 10:16:07
      Bean , Spring , 初始化 , 执行 , 接口 , 生命周期
      2025-03-31 08:50:08

      multiple select2内置ajax方法的正确使用

      multiple select2内置ajax方法的正确使用

      2025-03-31 08:50:08
      ajax , org , select
      2025-03-28 07:42:20

      Spring IOC 容器初始化流程深度解析

      Spring IOC 容器初始化流程深度解析

      2025-03-28 07:42:20
      Bean , IOC , Spring , 初始化 , 加载 , 容器
      查看更多
      推荐标签

      作者介绍

      天翼云小翼
      天翼云用户

      文章

      33561

      阅读量

      5266323

      查看更多

      最新文章

      SpringBoot学习(6)(Bean对象扫描)(@ComponentScan)

      2025-05-12 10:19:12

      Spring的 Aop的完整实现流程?

      2025-05-06 09:19:12

      【ETL工具】kettle 程序报错 Javascript error: TypeError: Cannot call method “trim“ of null

      2025-04-22 09:40:08

      深入理解Spring中的Bean循环依赖与解决机制

      2025-04-18 07:09:19

      java使用poi实现excel保护工作表实例代码(支持.xls和.xlsx)

      2025-04-09 09:15:47

      深入解析 Spring Bean 的生命周期

      2025-04-01 10:16:07

      查看更多

      热门文章

      Spring注解开发详细教程

      2023-06-15 06:37:58

      SpringBoot报错“To display the auto-configuration report re-run your application with ‘debug‘ enabled.“

      2023-06-13 08:29:18

      SpringBoot系列之设置上传文件大小的方式

      2023-06-13 08:34:11

      关于SpringBoot中左侧边栏各图标的含义

      2023-06-15 06:47:14

      Spring系列之常用接口,抽象类,工具类

      2023-06-19 06:57:41

      《面试1v1》SpringBean生命周期

      2023-06-14 09:11:31

      查看更多

      热门标签

      java Java python 编程开发 代码 开发语言 算法 线程 Python html 数组 C++ 元素 javascript c++
      查看更多

      相关产品

      弹性云主机

      随时自助获取、弹性伸缩的云服务器资源

      天翼云电脑(公众版)

      便捷、安全、高效的云电脑服务

      对象存储

      高品质、低成本的云上存储服务

      云硬盘

      为云上计算资源提供持久性块存储

      查看更多

      随机文章

      《面试1v1》SpringBean生命周期

      SpringBoot配置优先级+Bean各种声明应用管理(细节)

      Spring IOC 容器初始化流程深度解析

      《Spring 5官方文档》35. Spring注解编程模型

      Bean的拓展和应用

      SpringBoot报错“To display the auto-configuration report re-run your application with ‘debug‘ enabled.“

      • 7*24小时售后
      • 无忧退款
      • 免费备案
      • 专家服务
      售前咨询热线
      400-810-9889转1
      关注天翼云
      • 旗舰店
      • 天翼云APP
      • 天翼云微信公众号
      服务与支持
      • 备案中心
      • 售前咨询
      • 智能客服
      • 自助服务
      • 工单管理
      • 客户公告
      • 涉诈举报
      账户管理
      • 管理中心
      • 订单管理
      • 余额管理
      • 发票管理
      • 充值汇款
      • 续费管理
      快速入口
      • 天翼云旗舰店
      • 文档中心
      • 最新活动
      • 免费试用
      • 信任中心
      • 天翼云学堂
      云网生态
      • 甄选商城
      • 渠道合作
      • 云市场合作
      了解天翼云
      • 关于天翼云
      • 天翼云APP
      • 服务案例
      • 新闻资讯
      • 联系我们
      热门产品
      • 云电脑
      • 弹性云主机
      • 云电脑政企版
      • 天翼云手机
      • 云数据库
      • 对象存储
      • 云硬盘
      • Web应用防火墙
      • 服务器安全卫士
      • CDN加速
      热门推荐
      • 云服务备份
      • 边缘安全加速平台
      • 全站加速
      • 安全加速
      • 云服务器
      • 云主机
      • 智能边缘云
      • 应用编排服务
      • 微服务引擎
      • 共享流量包
      更多推荐
      • web应用防火墙
      • 密钥管理
      • 等保咨询
      • 安全专区
      • 应用运维管理
      • 云日志服务
      • 文档数据库服务
      • 云搜索服务
      • 数据湖探索
      • 数据仓库服务
      友情链接
      • 中国电信集团
      • 189邮箱
      • 天翼企业云盘
      • 天翼云盘
      ©2025 天翼云科技有限公司版权所有 增值电信业务经营许可证A2.B1.B2-20090001
      公司地址:北京市东城区青龙胡同甲1号、3号2幢2层205-32室
      • 用户协议
      • 隐私政策
      • 个人信息保护
      • 法律声明
      备案 京公网安备11010802043424号 京ICP备 2021034386号