ApplicationContextAware接口的setApplicationContext方法调用过程

SpringBoot中通过ApplicationContext获取RedisTemplate对象提示为空指针异常 1、定义一个工具类 package com.example.redis.utils; import com.example.redis.DemoApplication; import org.springframework.beans.BeansException; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; i 阅读详情

我们都知道实现了ApplicationContextAware接口的类会被调用setApplicationContext方法,从而获取到spring容器的上下文。但是这个调用过程缺很少有人知道,现在博主通过源码分析带大家掌握这个调用过程。

1、当我们启动spring容器的时候,我们执行到refresh()方法。
在这里插入图片描述
其中我们进入prepareBeanFactory(beanFactory);去看看。
在这里插入图片描述
我们看到一个new ApplicationContextAwareProcessor(this)类,这个类是一个在这里插入图片描述
BeanPostProcessor类型的类。OK,我们先在这里有一个印象,就是在BeanFactory里面加入了一个 ApplicationContextAwareProcessor。
这个过程就是ApplicationContextAwareProcessor的装配过程。

2、refresh()方法继续往下执行,执行到实例化bean的方法
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
代码执行到这个方法。

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(new StringValueResolver() {
				@Override
				public String resolveStringValue(String strVal) {
					return 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();
	}

最后会执行到beanFactory.preInstantiateSingletons();方法。
最终会执行到:

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
		// 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 != null ? instanceWrapper.getWrappedInstance() : null);
		Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);

		// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				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.isDebugEnabled()) {
				logger.debug("Eagerly caching bean '" + beanName +
						"' to allow for resolving potential circular references");
			}
			addSingletonFactory(beanName, new ObjectFactory<Object>() {
				@Override
				public Object getObject() throws BeansException {
					return getEarlyBeanReference(beanName, mbd, bean);
				}
			});
		}

		// Initialize the bean instance.
		Object exposedObject = bean;
		try {
			populateBean(beanName, mbd, instanceWrapper);
			if (exposedObject != null) {
				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<String>(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;
	}

这里注意看一下

if (exposedObject != null) {
				exposedObject = initializeBean(beanName, exposedObject, mbd);
}

这个代码,点进去看。
在这里插入图片描述
这个方法就是调用 ApplicationContextAwareProcessor的地方,我们进去看看。
在这里插入图片描述
我们可以看到,确实在BeanPostProcessors容器中有一个ApplicationContextAwareProcessor类。那么我们进到ApplicationContextAwareProcessor这个类的postProcessBeforeInitialization方法中。
在这里插入图片描述
在这里插入图片描述
根据这个源码,我们知道了,确实调用到了setApplicationContext方法。

但是我们要来个总结。
1、所有实例化的类都会走到ApplicationContextAwareProcessor这个类的postProcessBeforeInitialization方法中。
2、只有当当前正在实例化的类是Aware类型时,且是ApplicationContextAware类型时才会调用到setApplicationContext(this.applicationContext)方法把spring上下文设置进去。也就是实现了ApplicationContextAware接口。

**

OK,这既是ApplicationContextAware接口的setApplicationContext(this.applicationContext)方法调用全过程,希望能帮到大家,如果满意的同学,可以给个赞,谢谢!

**

FreeCAD MCP实战:用自然语言驱动AI建模,效率提升10倍 MCP(Model Context Protocol)是一种让AI模型调用外部工具和数据的协议标准,通过标准化通信层解决AI与CAD软件之间的交互难题。其原理是向AI暴露工具清单,AI根据自然语言需求自动选择工具并填充参数。在工程实践中,这一技术显著降低了CAD建模门槛,将重复性操作从手动点击转为语音指令,适用于批量零件生成、参数化设计等场景。FreeCAD作为开源CAD,凭借开放的Python API和脚本化能力,成为落地MCP的理想平台。本文基于FreeCAD MCP的实操经验,分享环境搭建、自然语言建 阅读详情

相关推荐

用C++手把手教你连接SimNow期货模拟盘:从CTP API封装到第一个订单(附完整代码)

本文详细介绍了如何使用C++连接SimNow期货模拟盘,从CTP API的基础架构解析到实现第一个订单的完整流程。内容涵盖CTP API的封装、SimNow环境配置、交易通道实现、行情接收与处理等核心环节,并提供完整代码示例,帮助开发者快速掌握量化交易中的期货模拟盘连接技术。

weixin_27215337的博客 333

ApplicationContextAware 的 setApplicationContext() 方法执行逻辑全解析

基本结论实现了ApplicationContextAware接口的类会被调用 setApplicationContext() 方法,从而获取到 Spring容器的上下文。org.springframework.context.ApplicationContextAware#setApplicationContext接口定义:public interface ApplicationContextAw...

AI天才研究院 1万+

从贝叶斯网络到结构因果模型:因果推理在可解释AI中的实践

在机器学习和数据分析领域,理解变量间的因果关系而不仅仅是统计关联,是构建可信赖、可解释系统的关键。概率图模型,特别是贝叶斯网络,通过有向无环图和条件概率表,能够高效地编码和推理变量间的条件依赖关系,广泛应用于医疗诊断、风险评估等场景。然而,贝叶斯网络主要刻画的是“是什么”的关联,难以回答“如果…会怎样”的因果问题。为了进行因果推断,需要引入结构因果模型和do-演算,它们通过定义结构方程和模拟干预操作,能够区分混杂效应,估计处理变量对结果变量的净因果影响。这一套方法论对于可解释人工智能至关重要,它能生成反事实

weixin_42168902的博客 382

【Spring 源码学习系列】ApplicationContextAware#setApplicationContext 方法的调用时机

纸上得来终觉浅,觉知此事需躬行。希望大家可以参考本文的简单Demo,亲自动手调试,理解才能更深刻。学习贵能举一反三。大家能够结合本节所学的方法自行分析方法的调用时机呢?本文并没有对IOC容器启动时的最核心方法中的refresh进行彻底的剖析,只是结合一个具体案例从某个切面去学习其中的某个环节,大家可以通过更多案例讲整个refresh核心方法都串起来,理解会越来越深入。httpshttpshttpshttpshttpshttpshttpshttpshttpshttps。....................

悟鸣的技术博客 2233

避开这5个坑!用MATLAB做核密度估计时90%人会犯的错误

本文详细解析了使用MATLAB进行核密度估计时常见的5个高频错误,包括三维数据可视化、带宽参数优化、大数据量处理、核函数选择及版本兼容性问题。特别针对核密度估计中的关键参数带宽(bandwidth)提供了数据驱动的优化策略,帮助用户提升分析精度与效率。

jenkins8butler的博客 278

Unity中5分钟实现3D高斯泼溅渲染:从原理到实战部署

3D高斯泼溅(3D Gaussian Splatting)是一种新兴的神经渲染技术,它通过显式地使用大量3D高斯椭球来表示场景,革新了传统的体渲染和神经辐射场(NeRF)方法。其核心原理是将这些3D高斯投影到2D屏幕并进行快速光栅化与Alpha混合,从而绕过了耗时的光线步进,实现了极高的渲染效率。这项技术的价值在于,它能够在消费级GPU上达到实时甚至超实时的帧率,同时保持紧凑的数据表达和惊人的视觉细节,极大地降低了高质量3D重建与渲染的门槛。在应用场景上,它正快速渗透到数字孪生、虚拟现实、文化遗产数字化以及

weixin_29474431的博客 279

详解Spring-ApplicationContext

详解Spring-ApplicationContext

欢迎朋友,我是一名十多年开发经验的新手,希望多多指教。 983

创客学院嵌入式驱动开发——学习资料汇总

1.创客学院知识巩固-01C语言回顾_C/C++_Set_Mode的博客-优快云博客https://blog.youkuaiyun.com/Set_Mode/article/details/94431050 2.创客学院知识巩固-02数据结构_Set_Mode的博客-优快云博客https://blog.youkuaiyun.com/Set_Mode/article/details/94431087 3.创客学院知...

snaking616 5118

ApplicationContextAware的setApplicationContext方法是什么时候执行的

ApplicationContextAware的setApplicationContext方法时什么时候执行的 可以肯定的是在从容器中getbean的过程中调用的,简单说下几个主要流程 getbean到调用bean后处理器 getbean的流程参见下图,主要参考标红字体部分 从图中可以看出,最后会调用initializeBeanf方法又会调用applyBeanPostProcesso...

tszxlzc的专栏 1万+

ACS运动控制器编程语言

ACS运动控制器采用SPiiPlusLanguage(SPL)作为核心编程语言,该语言基于C语法设计,内置丰富的运动控制指令,支持点位运动、插补等复杂控制。控制器提供专用开发工具SPiiPlusManager和ACSStudio,支持图形化编程与调试。同时兼容TCP/IP、EtherCAT等多种扩展接口,便于与上位机或PLC集成。使用时需注意实时性优先级、轴参数匹配等关键事项。官方文档和示例程序为开发者提供了完善的学习资源。

StevenChen的博客 628

JavaSwing_4.2: JDialog、JOptionPane(对话框)

JDialog,对话框。使用 JDialog 类可以创建自定义有的对话框,或者调用 JOptionPane 中的多个静态方法快速创建各种标准的对话框。JOptionPane是 JavaSwing 内部已实现好的,以静态方法的形式提供调用,能够快速方便的弹出要求用户提供值或向其发出通知的标准对话框。

谢TS的博客 7万+

关于通过实现ApplicationContextAware接口并重写setApplicationContext方法获取ApplicationContext的实例

关于通过实现ApplicationContextAware接口并重写setApplicationContext方法获取ApplicationContext的实例,这个要追溯到ApplicationContextAwareProcessor.java 看这个ApplicationContextAwareProcessor的invokeAwareInterfaces(Object bean) 方...

www.yiye.tech 3414

Vue3 - 详细实现虚拟列表前端虚拟滚动列表解决方案,vue3长列表优化之虚拟列表,解决列表动态高度不固定高度及图片视频图文异步请求加载问题,虚拟列表DOM大量数据同时加载渲染卡顿太慢及下滑列表闪烁

vue3,vue3虚拟列表,用vue3实现一个虚拟列表,长列表高度不一致如何实现虚拟滚动加载列表,虚拟列表有图片视频,图文列表,上万条数据同时渲染解决,长列表dom渲染太卡,列表滚动条加载超多数据,瀑布流,在Vue3中如何实现列表的虚拟滚动,虚拟列表滑动白屏闪烁闪一下,虚拟列表每个项的高度不确定,可动态改变高度,vue3虚拟滚动列表,页面数据太多加载很慢怎么办,vue3实现不定高的虚拟列表,定高和不定高,虚拟列表非固定高度,vue3长列表优化之虚拟列表实现,vue3虚拟列表高度不固定,用vue3实现一个虚拟

🏆 前端领域优质创作者 1万+

Spring之Bean实现了ApplicationContextAware等aware接口,对于setApplicationContext方法执行时间点的说明

对于实现了Aware接口的Bean对象,如: public class beanTest implement ApplicationContextAware { private static ApplicationContext applicationContext; public void setApplicationContext(ApplicationContext app

fycghy0803的专栏 6696

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

Spring之ApplicationContextAware接口详解

在Spring中,当一个bean实现了ApplicationContextAware接口,这个bean便可以获取到ApplicationContext对象,进而获取应用上下文中的bean。 代码实例 package com.huawei.nlz.springplayground.applicationcontextaware; import org.springframework.bean...

拈花的专栏 1076

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

ApplicationContextAware的理解

当一个类实现了ApplicationContextAware之后,这个类就可以方便获得ApplicationContext中的所有bean,这个类可以直接获取spring配置文件中,所有有引用到的bean对象。 @Component public final class ApplicationContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext;

605

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

Spring中ApplicationContextAware的使用理解

当一个类实现了ApplicationContextAware接口之后,这个类就可以方便的获得ApplicationContext对象(Spring上下文),Spring发现某个Bean实现了ApplicationContextAware接口,Spring容器会在创建该Bean之后,自动调用该Bean的setApplicationContext(参数)方法,调用该方法时,会将容器本身ApplicationContext对象()作为参数传递给该方法,通过这个上下文环境对象得到Spring容器中的Bean。

北辰 599

ApplicationContextAware得到ApplicationContext的原理

Spring中,普通bean可以通过实现ApplicationContextAware得到ApplicationContext,需要重写setApplicationContext和getApplicationContext两个方法。我们知道,是通过setApplicationContext将spring的当前的applicationContext得到,那么spring是什么时候执行setAppli

Freewind的技术专栏 8833

SpringApplication的启动过程

spring boot 的一个启动流程,底层分析SpringApplication.run(Application.class, args);

qq_44885775的博客 1799

高仿真的类-ApplicationContextAware

/** * 通过解耦方式获得IOC容器的顶层设计 * 后面将通过一个监听器去扫描所有的类,只要实现了此接口, * 将自动调用setApplicationContext()方法,从而将IOC容器注入到目标类中 */ public interface V1ApplicationContextAware { void setApplicationContext(V1ApplicationContext applicationContext); } ...

Leon_Jinhai_Sun的博客 131

Spring中的ApplicationContextAware使用

加载Spring配置文件时,如果Spring配置文件中所定义的Bean类实现了ApplicationContextAware 接口,那么在加载Spring配置文件时,会自动调用ApplicationContextAware 接口中的public void setApplicationContext(ApplicationContext applicationContex...

weixin_30736301的博客 132

在非spring管理的类中获取spring容器中的 bean

实现ApplicationContextAware接口,重写setApplicationContext方法: @Service public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; /** * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.

weixin_38860401的博客 1641

在spring上下文中获取bean

使用spring技术的web应用中,如何在程序中获取Spring上下文ApplicationContext,有两种方式: 1:实现ApplicationContextAware接口(实现此接口的setApplicationContext方法),在web应用中,spring会在启动时加载springContext上下文,spring的配置文件中配置了&lt;context:component-...

cc_weige的专栏 886

bean获取Spring容器

Person.java 1 public class Person implements ApplicationContextAware{ 2 3 private String name; 4 private int age; 5 private doHomeWork dohomework; 6 private Applicatio...

weixin_30457065的博客 100

SpringBoot获取配置给静态属性赋值

实现方式 实现ApplicationContextAware类,重写setApplicationContext方法,并且添加@Component注解 @Component public class SpringUtils implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationCont

YGangHeng的博客 2359

用@Component注解的类中@Autowired为null

编写一个工具类实现ApplicationContextAware接口,重写setApplicationContext方法 @Component public class ApplicationContextUtils implements ApplicationContextAware { private static ApplicationContext context; /** * Set the ApplicationContext that this object

千羽公子的专栏 1272
上一篇: spring事务从底层掌握其实现原理
下一篇: 源码分析FactoryBean接口不为人知的秘密
Jack爱258
博客等级 码龄10年 1288粉丝 124原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值