Spring源码解读之创建bean

news2024/12/24 8:54:53

本文章我们会解读一下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}  ---key
		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.
		// 实例化非懒加载的单例Bean
		beanFactory.preInstantiateSingletons();
	}

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

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

点击进入

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

@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) {
			// 获取合并后的BeanDefinition
			RootBeanDefinition 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()这个方法

@Override
	public 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就是id
		String beanName = transformedBeanName(name);
		Object beanInstance;

		// Eagerly check singleton cache for manually registered singletons.
		//先在单例池中去获取bean
		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(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---->&xxx
				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);
			}


			//JFR代码运行机制
			StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")
					.tag("beanName", name);
			try {
				if (requiredType != null) {
					beanCreation.tag("beanType", requiredType::toString);
				}
				//取出名字对应的合并后的beanDefinition
				RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);

				// 检查BeanDefinition是不是Abstract的,如果是Abstract  报错
				checkMergedBeanDefinition(mbd, beanName, args);

				// Guarantee initialization of beans that the current bean depends on.
				//创建当前bean之前,先需要创建@dependsOn里面的bean
				String[] 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为value
						registerDependentBean(dep, beanName);

						// 创建所依赖的bean
						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()) {// 创建单例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的类型是否是requiredType
		return 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
	 */
	@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.
		// 马上就要实例化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.coloradmin.cn/o/1262826.html

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

相关文章

人工智能-产生式系统实验(动物识别)

1.实验目的 1.熟悉知识的表示方法 2.掌握产生式系统的运行机制 3.产生式系统推理的基本方法。 2.实验内容 运用所学知识&#xff0c;设计并编程实现一个小型动物识别系统&#xff0c;能识别虎、金钱豹、斑马、长颈鹿、鸵鸟、企鹅、信天翁等七种动物的产生式系统。 规则库&…

什么是虚拟化?如何监控虚拟化设备

虚拟化是创建物理 IT 资源&#xff08;如服务器或桌面&#xff09;的虚拟版本的行为&#xff0c;虚拟机&#xff08;VM&#xff09;是在物理主机设备上创建的&#xff0c;VM 的行为与物理设备完全相同&#xff0c;并且可以从主机运行不同的操作系统。 例如&#xff0c;您可以在…

centos服务器扩容

centos服务器扩容 我的情况是&#xff0c;原服务器是一个80g磁盘&#xff0c;管理员又追加了120G到这块磁盘上&#xff0c;需要把这120G重新追加使用。 请确认你遇到的情况是否和我初始截图一致&#xff0c;再往下看&#xff0c;免得浪费时间与精力 服务器中有120G尚未使用&…

智能测径仪从这五大方面提升了性能

在测径仪的研发升级中&#xff0c;蓝鹏测控从未停下脚步&#xff0c;研究新的技术&#xff0c;让测径仪更好的为产线服务的功能。目前提供两种类型的在线测径仪&#xff0c;普通测径仪与智能测径仪&#xff0c;智能型主要在这五大方面进行了性能提升。 1、自动化程度 智能测径…

Update this scope and remove the “systemPath“

问题 解析&#xff1a; 在特定的指定路径上查找系统相关性。这大大降低了可移植性&#xff0c;因为如果您将工件部署在一个与您的环境不同的环境中&#xff0c;代码将无法工作。 解决&#xff1a; 1 使用官方maven仓库的第三方jar包 2 如果官方仓库不存在jar包&#xff0c;…

抖去推--短视频账号矩阵系统saas工具源码技术开发(源头)

一、短视频矩阵系统搭建常见问题&#xff1f; 1、抖去推的短视频AI矩阵营销软件需要一定的技术水平吗&#xff1f; 答&#xff1a;不需要。产品简单易用&#xff0c;不需要具备专业的技术水平&#xff0c;即使是初学者&#xff0c;也能够轻松上手操作。 3、抖去推的短视频AI矩…

E云管家微信群聊机器人开发

请求URL&#xff1a; http://域名地址/modifyGroupRemark 请求方式&#xff1a; POST 请求头Headers&#xff1a; Content-Type&#xff1a;application/jsonAuthorization&#xff1a;login接口返回 参数&#xff1a; 参数名必选类型说明wId是String登录实例标识chatRo…

my.ini添加了一句后又删除了,重启却失败的解决办法

背景&#xff1a;添加了一句&#xff0c;然后保存了&#xff0c;之后打开删掉了&#xff0c;结果就无法启动了&#xff0c;最后另存为ANSI格式&#xff0c;再把这个格式文件覆盖my.ini即可解决

有哪些程序员兼职接单的网站可以推荐?

话说程序员这个职业有个好处就是可以给自己打工&#xff0c;只要掌握了一技之长&#xff0c;就可以到外面接私活&#xff0c;一方面增加了自己的收入&#xff0c;另一方面还锻炼了自己的技术。 相信很多新手程序员&#xff0c;都希望能迅速提高自己的能力同时&#xff0c;又可…

flutter 文本不随系统设置而改变大小[最全的整理]

文本不随系统设置而改变大小[三] 前言方案十三&#xff1a;使用Flexible方案十四&#xff1a;使用MediaQueryData的textScaleFactor属性方案十五&#xff1a;使用FractionallySizedBox方案十六&#xff1a;使用自定义文本样式方案十七&#xff1a;使用自定义绘制&#xff08;Cu…

接口测试及常用接口测试工具(含文档)

首先&#xff0c;什么是接口呢&#xff1f; 接口一般来说有两种&#xff0c;一种是程序内部的接口&#xff0c;一种是系统对外的接口。 系统对外的接口&#xff1a;比如你要从别的网站或服务器上获取资源或信息&#xff0c;别人肯定不会把数据库共享给你&#xff0c;他只能给你…

MFC哈希实现 目标:知道初始密码的人,才能改密码及登录。只知道登录密码只能登录。避免密码直接写在代码里或本地,通过软件评估报告。----安全行业基础5

一种简单的登录设计&#xff0c;密码保存在本地。&#xff08;直接MD5不安全&#xff0c;别人可以更换本地的密码,得再加一层算法就相对安全一点&#xff09; 当然也可以用加密机或专门存密码的系统来实现&#xff0c;就过于复杂。目标&#xff1a;1、为了避免密码直接写在代码…

eNSP防火墙USG6000V使用Web界面登入教程

文章目录 登入流程1、下载USG6000V的镜像包2、导入USG6000V的镜像包3、配置防火墙web页面4、修改本机vmnet1网卡的ipv4地址5、在eNSP上添加云6、配置防火墙管理地址&#xff0c;开启http服务7、关闭电脑防火墙8、访问web页面 登入流程 1、下载USG6000V的镜像包 链接&#xff…

数字人担任展会虚拟主持人,如何释放大会新活力?

近日&#xff0c;虚拟主持人谷小雨解锁新身份&#xff0c;作为第二届全球数字贸易博览会的“数字新闻官”为大众播报展会的热门新闻话题&#xff0c;带领大众探索未来数字贸易的无限可能。 *图片源于网络 随着元宇宙的概念更多地深入各领域&#xff0c;数字人多次以虚拟主持人或…

Docker | 自定义Docker镜像

✅作者简介&#xff1a;大家好&#xff0c;我是Leo&#xff0c;热爱Java后端开发者&#xff0c;一个想要与大家共同进步的男人&#x1f609;&#x1f609; &#x1f34e;个人主页&#xff1a;Leo的博客 &#x1f49e;当前专栏&#xff1a;Docker系列 ✨特色专栏&#xff1a; My…

Spring---IOC与DI

文章目录 什么是Spring&#xff1f;什么是Ioc&#xff1f;通过代码案例理解总结代码案例真正理解Ioc 什么是DI&#xff1f; 什么是Spring&#xff1f; Spring指的是 Spring Framework &#xff08;Spring框架&#xff09;&#xff0c;它是一个开源的框架&#xff0c;有着活跃而…

【带头学C++】----- 八、C++面向对象编程 ---- 8.7 引用(Reference)

目录 8.7 引用&#xff08;Reference&#xff09; 8.7.1 普通变量引用 8.7.2 数组引用 8.7.3 指针变量的引用方法 8.7.4 函数的引用 8.7.5 引用作为函数的参数 8.7.6 引用作为函数的返回值类型 1. 返回值类型不用使用局部变量的引用类型 2.返回值类型为引用&#xff0…

es集群相关报错信息

给es集群添加用户密码的时候&#xff0c;会自动弹出相关的账户信息&#xff0c;这个时候&#xff0c;只需要设置对应密码就可以了 [esuserjky-test1 bin]$ ./elasticsearch-setup-passwords interactive future versions of Elasticsearch will require Java 11; your Java ve…

【Linux】了解进程的基础知识

进程 1. 进程的概念1.1 进程的理解1.2 Linux下的进程1.3 查看进程属性1.4 getpid和getppid 2. 创建进程3. 进程状态4. 进程优先级5. 进程切换6. 环境变量7. 本地变量与内建命令 1. 进程的概念 一个已经加载到内存中的程序&#xff0c;叫做进程&#xff08;也叫任务&#xff09…

2021年全国硕士研究生入学统一考试管理类专业学位联考英语(二)试题

文章目录 2021年全国硕士研究生入学招生考试英语二试题SectionⅠUse of EnglishSection Ⅱ Reading ComprehensionText 1Text 2Text 2Text 3Text 4 Section III TranslationSection Ⅳ Writing 2021年全国硕士研究生入学招生考试英语二试题 SectionⅠUse of English Directio…