Spring源码解读之创建bean

本文章我们会解读一下Spring如何根据beanDefinition创建bean的;

代码入口:

AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);applicationContext.refresh();

当spring执行refresh()这个方法进行上下文刷新时, 会进行非懒加载的bean的创建,创建非懒加载的bean的源码入口为:

finishBeanFactoryInitialization(beanFactory);

 该方法的具体实现:

/*** 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.// 如果BeanFactory中存在名字叫conversionService的Bean,则设置为BeanFactory的conversionService属性// ConversionService是用来进行类型转化的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 BeanFactoryPostProcessor// (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:// at this point, primarily for resolution in annotation attribute values.// 设置默认的占位符解析器  ${xxx}  ---keyif (!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.// 实例化非懒加载的单例BeanbeanFactory.preInstantiateSingletons();}

上述方法中,进行实例化非懒加载的单例bean的代码是

		// 实例化非懒加载的单例BeanbeanFactory.preInstantiateSingletons();

点击进入

DefaultListableBeanFactory.java的public void preInstantiateSingletons() 的方法;

@Overridepublic 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) {// 获取合并后的BeanDefinitionRootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);//bd.isAbstract() 是不是抽象的BeanDefinition  一般是xml定义的  抽象的beanDefinition不会被创建if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {if (isFactoryBean(beanName)) {// 获取FactoryBean对象Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);if (bean instanceof FactoryBean) {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) {// 创建真正的Bean对象(getObject()返回的对象)getBean(beanName);}}}else {// 创建Bean对象getBean(beanName);}}}// 所有的非懒加载单例Bean都创建完了后// Trigger post-initialization callback for all applicable beans...for (String beanName : beanNames) {Object singletonInstance = getSingleton(beanName);if (singletonInstance instanceof SmartInitializingSingleton) {StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize").tag("beanName", beanName);SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;if (System.getSecurityManager() != null) {AccessController.doPrivileged((PrivilegedAction<Object>) () -> {smartSingleton.afterSingletonsInstantiated();return null;}, getAccessControlContext());}else {smartSingleton.afterSingletonsInstantiated();}smartInitialize.end();}}}

此方法中 getBean(beanName);会创建bean;我们进入getBean()这个方法

@Overridepublic Object getBean(String name) throws BeansException {return doGetBean(name, null, null, false);}

然后我们进入doGetBean(name, null, null, false)这个方法,主要判断该bean的类型然后根据具体情况进行调用protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) 创建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(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)throws BeansException {//对beanName做处理// name有可能是 &xxx 或者 xxx,如果name是&xxx,那么beanName就是xxx// name有可能传入进来的是别名,那么beanName就是idString beanName = transformedBeanName(name);Object beanInstance;// Eagerly check singleton cache for manually registered singletons.//先在单例池中去获取beanObject 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(sharedInstance)是FactoryBean,需要对该bean进行进一步处理beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);}else {	//如果在单例池中没有获取到bean// 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();//containsBeanDefinition(beanName) 检测spring容器中有没有这个名字的bean//当前容器中没有找到,去父工厂找if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {// Not found -> check parent.// &&&&xxx---->&xxxString 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);}//JFR代码运行机制StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate").tag("beanName", name);try {if (requiredType != null) {beanCreation.tag("beanType", requiredType::toString);}//取出名字对应的合并后的beanDefinitionRootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);// 检查BeanDefinition是不是Abstract的,如果是Abstract  报错checkMergedBeanDefinition(mbd, beanName, args);// Guarantee initialization of beans that the current bean depends on.//创建当前bean之前,先需要创建@dependsOn里面的beanString[] dependsOn = mbd.getDependsOn();if (dependsOn != null) {// dependsOn表示当前beanName所依赖的,当前Bean创建之前dependsOn所依赖的Bean必须已经创建好了for (String dep : dependsOn) {// beanName是不是被dep依赖了,如果是则出现了循环依赖if (isDependent(beanName, dep)) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");}// dep被beanName依赖了,存入dependentBeanMap中,dep为key,beanName为valueregisterDependentBean(dep, beanName);// 创建所依赖的beantry {getBean(dep);}catch (NoSuchBeanDefinitionException ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,"'" + beanName + "' depends on missing bean '" + dep + "'", ex);}}}// Create bean instance.if (mbd.isSingleton()) {// 创建单例bean的逻辑: 先从缓存中拿,如果没有的,再创建该bean,并且存入单例缓存中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;}});beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);}else if (mbd.isPrototype()) {//创建原型bean的逻辑:直接创建对象// It's a prototype -> create a new instance.Object prototypeInstance = null;try {beforePrototypeCreation(beanName);prototypeInstance = createBean(beanName, mbd, args);}finally {afterPrototypeCreation(beanName);}beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);}else {//有作用域相关注解的bean  例如request、session等获取scope作用域注解信息String scopeName = mbd.getScope();if (!StringUtils.hasLength(scopeName)) {throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");}Scope scope = this.scopes.get(scopeName);if (scope == null) {throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");}try {  // session.getAttriute(beaName)  setAttri//类似非懒加载单例bean的创建,先从缓存中取,取不到,创建bean且放入缓存Object scopedInstance = scope.get(beanName, () -> {beforePrototypeCreation(beanName);try {return createBean(beanName, mbd, args);}finally {afterPrototypeCreation(beanName);}});beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);}catch (IllegalStateException ex) {throw new ScopeNotActiveException(beanName, scopeName, ex);}}}catch (BeansException ex) {beanCreation.tag("exception", ex.getClass().toString());beanCreation.tag("message", String.valueOf(ex.getMessage()));cleanupAfterBeanCreationFailure(beanName);throw ex;}finally {beanCreation.end();}}// 检查通过name所获得到的beanInstance的类型是否是requiredTypereturn adaptBeanInstance(name, beanInstance, requiredType);}

进入protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) ,这里会进行bean的实例化。

/*** Central method of this class: creates a bean instance,* populates the bean instance, applies post-processors, etc.* @see #doCreateBean*/@Overrideprotected 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.// 马上就要实例化Bean了,确保beanClass被加载了,进行类加载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.// 实例化前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);}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/178388.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Jmeter+influxdb+grafana监控平台在windows环境的搭建

原理&#xff1a;Jmeter采集的数据存储在infuxdb数据库中&#xff0c;grafana将数据库中的数据在界面上进行展示 一、grafana下载安装 Download Grafana | Grafana Labs 直接选择zip包下载&#xff0c;下载后解压即可&#xff0c;我之前下载过比较老的版本&#xff0c;这里就…

在 The Sandbox 设置总部,SCB 10X 和 T-POP 为 4EVE 元宇宙音乐会揭幕

协作学习为全球粉丝提供了无限的可能性&#xff0c;让他们通过革命性的元宇宙体验沉浸在泰国流行文化中。 作为 SCBX 集团背后的创新力量&#xff0c;SCB 10X 很高兴宣布与 T-POP Incorporation 展开开创性合作&#xff0c;T-POP Incorporation 是泰国流行文化在全球舞台上的领…

鸿蒙开发已成新趋势

随着华为鸿蒙操作系统的快速崭露头角&#xff0c;鸿蒙开发已然成为当前技术领域的热门新趋势。本文将深入探讨鸿蒙开发的重要性和独特优势&#xff0c;并详细介绍一些关键的鸿蒙开发技术和工具&#xff0c;以及它们对开发者个人和整个行业带来的深远影响。 首先&#xff0c;鸿蒙…

入侵redis之准备---VMware安装部署kail镜像服务器【详细包含云盘镜像】

入侵redis之准备—VMware安装部署kail镜像服务器【详细包含云盘镜像】 kail是一个很好玩的操作系统&#xff0c;不多说了哈 下载kail镜像 kail官网:https://www.kali.org/get-kali/#kali-platforms 百度云盘下载&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1PRjo…

具身智能17篇创新性论文及代码合集,2023最新

今天来聊聊人工智能领域近期的一个热门研究方向——具身智能。 具身智能&#xff08;Embodied Intelligence&#xff09;指的是机器人或智能体通过感知、理解和交互来适应环境&#xff0c;并执行任务的能力。与传统的基于规则或符号的人工智能不同&#xff0c;具身智能强调将感…

基于springboot实现私人健身与教练预约管理系统项目【项目源码+论文说明】计算机毕业设计

基于springboot实现私人健身与教练预约管理系统演示 摘要 随着信息技术和网络技术的飞速发展&#xff0c;人类已进入全新信息化时代&#xff0c;传统管理技术已无法高效&#xff0c;便捷地管理信息。为了迎合时代需求&#xff0c;优化管理效率&#xff0c;各种各样的管理系统应…

hello vtk 圆柱

VTK 可视化的流程及步骤 标题引入VTK库和初始化&#xff1a; 引入 VTK 库和 AutoInit 模块&#xff0c;以便使用 VTK 的渲染和交互功能 设置背景颜色和颜色对象&#xff1a; 使用 vtkNamedColors 设置背景颜色和演员颜色。 创建圆柱体源&#xff1a; 使用 vtkCylinderSou…

蓝桥杯-01简介

文章目录 蓝桥杯简介参考资源蓝桥杯官网第15届大赛章程一、概况&#xff08;一&#xff09;大赛背景和宗旨&#xff08;二&#xff09;大赛特色&#xff08;三&#xff09;大赛项目1.Java软件开发2.C/C程序设计3.Python程序设计4.Web应用开发5.软件测试6.网络安全7.嵌入式设计与…

可视化文件编辑与SSH传输神器WinSCP如何公网远程本地服务器

可视化文件编辑与SSH传输神器WinSCP如何公网远程本地服务器 文章目录 可视化文件编辑与SSH传输神器WinSCP如何公网远程本地服务器1. 简介2. 软件下载安装&#xff1a;3. SSH链接服务器4. WinSCP使用公网TCP地址链接本地服务器5. WinSCP使用固定公网TCP地址访问服务器 1. 简介 …

CH02_交给子类

Template Method模式 组成模板的方法被定义在父类中&#xff0c;由于这些方法是抽象方法&#xff0c;所以只查看父类的代码是无法知道这些方法最终会进行何种具体处理的。唯一能知道的就是父类如何调用这些方法。 类图 说明 AbstractClass&#xff08;抽象类&#xff09; Abs…

vue项目中通过vuex管理数据

目录 1.前言&#xff1a; 2.vuex的基础用法&#xff1a; 1.构建与挂载vue 基础模板渲染 构建仓库 2.mutations的使用 1.介绍 ​编辑 2.案列&#xff1a; 3.传参 4.辅助函数mapMutations&#xff1a; 3.module分对象的写法 介绍 建立模块&#xff1a; 访问数据的方…

【VROC】看Intel VROC如何给NVMe SSD做RAID

在当今对硬盘性能要求越来越高的环境中&#xff0c;SATA和SAS接口由于自身的限制&#xff0c;其性能很难突破600MiB/s的瓶颈。因此&#xff0c;对于需要更高底层硬件性能的行业&#xff0c;如数据库等&#xff0c;对NVMe盘的需求越来越迫切。然而&#xff0c;NVMe盘直通到CPU&a…

三种常见的哈希结构

1.数组 2.set 使用序引用set头文件 unordered_set需引用unordered_set 3.map unordered_map需引用unordered_map头文件

error: ‘PixelPacket’ in namespace ‘Magick’ does not name a type

最近做一个项目需要配置ImageMagick库&#xff0c;本项目配置环境如下&#xff1a; ImageMagick version 7 Operating system, version and so on ubuntu 20.04 Descriptionerror: ‘PixelPacket’ in namespace ‘Magick’ does not name a type 这是在运行程序时候出现的问题…

优维低代码实践:搜索功能

优维低代码技术专栏&#xff0c;是一个全新的、技术为主的专栏&#xff0c;由优维技术委员会成员执笔&#xff0c;基于优维7年低代码技术研发及运维成果&#xff0c;主要介绍低代码相关的技术原理及架构逻辑&#xff0c;目的是给广大运维人提供一个技术交流与学习的平台。 优维…

设单链表中有仅三类字符的数据元素(大写字母、数字和其它字符),要求利用原单链表中结点空间设计出三个单链表的算法,使每个单链表只包含同类字符。

使用C语言编写的算法,将原单链表根据字符类型拆分为三个单链表。其中,大写字母链表(upperList)、数字链表(digitList)和其他字符链表(otherList)分别用于存储相应类型的字符。 `Upper Case List`存储了大写字母A、C, `Digit List`存储了数字1、2、3, `Other List`存…

C语言数据结构-----栈和队列练习题(分析+代码)

前言 前面的博客写了如何实现栈和队列&#xff0c;下来我们来看一下队列和栈的相关习题。 链接: 栈和队列的实现 文章目录 前言1.用栈实现括号匹配2.用队列实现栈3.用栈实现队列4.设计循环队列 1.用栈实现括号匹配 此题最重要的就是数量匹配和顺序匹配。 用栈可以完美的做到…

Egg.js中Cookie和Session

Cookie HTTP请求是无状态的&#xff0c;但是在开发时&#xff0c;有些情况是需要知道请求的人是谁的。为了解决这个问题&#xff0c;HTTP协议设计了一个特殊的请求头&#xff1a;Cookie。服务端可以通过响应头&#xff08;set-cookie&#xff09;将少量数据响应给客户端&#…

电子学会C/C++编程等级考试2023年03月(二级)真题解析

C/C++等级考试(1~8级)全部真题・点这里 第1题:数字字符求和 请编写一个程序实现以下功能:从一个字符串中,提取出所有的数字字符即0-9,并作为数求和。 时间限制:1000 内存限制:65536输入 一行字符串,长度不超过100,字符串中不含空格。输出 字符串中所有数字字符作为数…

三维gis中用纹理限定多边形地理区域

在三维 gis 中经常需要在指定的多边形地理范围内做一些操作&#xff0c;比如地形的多边形裁剪、压平多边形区域内的倾斜摄影模型、在指定地理范围内绘制等间距的点等。这都涉及到限定多边形区域的问题。 所谓的限定多边形地理区域&#xff0c;核心问题在于判断某个片元是否处于…