Spring 源码阅读

news2024/12/24 8:16:05

 1. beanFactory

     The root interface for accessing a Spring bean container.

2. BeanFactoryPostProcessor

     对bean定义进行后置处理,比如jdbc类读取配置的密码,用户名等。

3.BeanPostProcessor

public interface BeanPostProcessor {
    Object postProcessBeforeInitialization(Object var1, String var2) throws BeansException;

    Object postProcessAfterInitialization(Object var1, String var2) throws BeansException;
}

 4. Enviroment接口,加载系统环境变量和属性值

5. 源码部分

@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) {
				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;
			}
		}

1. 创建容器obtainfreshBeanFactory,-> refreshBeanFactory.  ->DefaultlistableBeanFactory, 

2. 给beanFactory赋值  customizeBeanFactory

/**
	 * This implementation performs an actual refresh of this context's underlying
	 * bean factory, shutting down the previous bean factory (if any) and
	 * initializing a fresh bean factory for the next phase of the context's lifecycle.
	 */
	@Override
	protected final void refreshBeanFactory() throws BeansException {
		if (hasBeanFactory()) {
			destroyBeans();
			closeBeanFactory();
		}
		try {
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			beanFactory.setSerializationId(getId());
			customizeBeanFactory(beanFactory);
			loadBeanDefinitions(beanFactory);
			synchronized (this.beanFactoryMonitor) {
				this.beanFactory = beanFactory;
			}
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
	}

3. 加载bean定义,以读取xml的ApplicationContext为例

Override
	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// Create a new XmlBeanDefinitionReader for the given BeanFactory.
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		// Configure the bean definition reader with this context's
		// resource loading environment.
		beanDefinitionReader.setEnvironment(this.getEnvironment());
		beanDefinitionReader.setResourceLoader(this);
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

		// Allow a subclass to provide custom initialization of the reader,
		// then proceed with actually loading the bean definitions.
		initBeanDefinitionReader(beanDefinitionReader);
		loadBeanDefinitions(beanDefinitionReader);
	}

4. 调用beanFactoryProcessor的后置增强处理器

invokeBeanFactoryPostProcessors(beanFactory);

5. 注册beanPostProcessor

doGetBean - createBean -doCreateBean, doGetBean 时getSingleton放到三级缓存中

7. 

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;
	}
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged(new PrivilegedAction<Object>() {
				@Override
				public Object run() {
					invokeAwareMethods(beanName, bean);
					return null;
				}
			}, getAccessControlContext());
		}
		else {
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			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;
	}
@Override
	public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
		// Don't override the class with CGLIB if no overrides.
		if (bd.getMethodOverrides().isEmpty()) {
			Constructor<?> constructorToUse;
			synchronized (bd.constructorArgumentLock) {
				constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
				if (constructorToUse == null) {
					final Class<?> clazz = bd.getBeanClass();
					if (clazz.isInterface()) {
						throw new BeanInstantiationException(clazz, "Specified class is an interface");
					}
					try {
						if (System.getSecurityManager() != null) {
							constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
								@Override
								public Constructor<?> run() throws Exception {
									return clazz.getDeclaredConstructor((Class[]) null);
								}
							});
						}
						else {
							constructorToUse =	clazz.getDeclaredConstructor((Class[]) null);
						}
						bd.resolvedConstructorOrFactoryMethod = constructorToUse;
					}
					catch (Exception ex) {
						throw new BeanInstantiationException(clazz, "No default constructor found", ex);
					}
				}
			}
			return BeanUtils.instantiateClass(constructorToUse);
		}
		else {
			// Must generate CGLIB subclass.
			return instantiateWithMethodInjection(bd, beanName, owner);
		}
	}
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
		Assert.notNull(ctor, "Constructor must not be null");
		try {
			ReflectionUtils.makeAccessible(ctor);
			return ctor.newInstance(args);
		}
		catch (InstantiationException ex) {
			throw new BeanInstantiationException(ctor.getDeclaringClass(),
					"Is it an abstract class?", ex);
		}
		catch (IllegalAccessException ex) {
			throw new BeanInstantiationException(ctor.getDeclaringClass(),
					"Is the constructor accessible?", ex);
		}
		catch (IllegalArgumentException ex) {
			throw new BeanInstantiationException(ctor.getDeclaringClass(),
					"Illegal arguments for constructor", ex);
		}
		catch (InvocationTargetException ex) {
			throw new BeanInstantiationException(ctor.getDeclaringClass(),
					"Constructor threw exception", ex.getTargetException());
		}
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
		if (System.getSecurityManager() != null) {
			AccessController.doPrivileged(new PrivilegedAction<Object>() {
				@Override
				public Object run() {
					invokeAwareMethods(beanName, bean);
					return null;
				}
			}, getAccessControlContext());
		}
		else {
			invokeAwareMethods(beanName, bean);
		}

		Object wrappedBean = bean;
		if (mbd == null || !mbd.isSynthetic()) {
			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;
	}

5. 初始化广播器

    注册监听器

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

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

相关文章

ctfshow--RCE极限挑战

本周ctfshow的挑战注重点为RCE&#xff0c;主要利用是&#xff1a;自增绕过RCE RCE挑战1 属于简单类型 源码 error_reporting(0); highlight_file(__FILE__); $code $_POST[code]; $code str_replace("(","括号",$code); $code str_replace(".&q…

Arcgis使用教程(十一)ARCGIS地图制图之经纬网格设置参数详解

Arcgis地图制图中&#xff0c;经纬网格的添加详细参见&#xff1a; Arcgis使用教程&#xff08;十&#xff09;ARCGIS地图制图之经纬网格添加_空中旋转篮球的博客-CSDN博客 1.加载数据 在Arcmap中加载中国矢量图层数据&#xff08;中国省级行政区图&#xff0c;国界线两个图层…

善于使用二阶思维

事情往往不是你想象的那样&#xff0c;有时候&#xff0c;看似解决了问题&#xff0c;却在不经意间&#xff0c;引发了更严重的后果。帮助我们思考、决策、解决问题的最有效方法是&#xff0c;运用二阶思维。 什么是二阶思维&#xff1f; 一阶思维是单纯而肤浅的&#xff0c;几…

34.nacos客户端读取共享配置文件实例(springcloud)

其他配置环境和上文相同&#xff0c;本实例不再演示 https://blog.csdn.net/weixin_59334478/article/details/127953755?spm1001.2014.3001.5501https://blog.csdn.net/weixin_59334478/article/details/127953755?spm1001.2014.3001.55011.新建共享配置文件&#xff0c;使…

高NA (数值孔径)物镜的分析

高NA(数值孔径)物镜常用于光学显微及光刻&#xff0c;并已广泛在其他应用中得以使用。众所周知&#xff0c;在高数值孔径物镜的使用中&#xff0c;电磁场矢量特性的影响是不可忽略的。一个众所周知的例子就是由高NA(数值孔径)物镜聚焦线性偏振圆光束时&#xff0c;焦斑的不对称…

过控Matlab-实验法建立被控过程的数学模型(一)

太原理工大学过程控制实验之实验法建立被控过程的数学模型 过控Matlab实验法建立被控过程的数学模型实验内容1.利用MATLAB根据作图法建立系统的一阶惯性环节加纯迟延的近似数学模型。2.利用MATLAB根据计算法建立系统的一阶惯性环节加纯迟延的近似数学模型。3.利用MATLAB根据计算…

[附源码]计算机毕业设计JAVA基于JSP社区生鲜配送系统

[附源码]计算机毕业设计JAVA基于JSP社区生鲜配送系统 项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; SSM …

[附源码]java毕业设计网上手机商城

项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; SSM mybatis Maven Vue 等等组成&#xff0c;B/S模式 M…

驱动开发基础

1、Hello驱动 我们应用程序使用open函数的时候&#xff0c;会调用内核的sys_open函数&#xff0c;然后接下来 1、然后打开普通文件的话会使用文件系统操作硬件&#xff0c; 2、要是打开驱动文件&#xff0c;会使用驱动程序对应的drv_open函数 怎么写驱动程序 我们驱动对应的d…

了解 Oracle 中的视图

一、概念 视图是基于一个或者多个表上的预定义查询&#xff0c;这些表称为基表&#xff0c;从视图中查询数据的方法与从基表中查询数据的方法相同。视图是一个查看数据的窗口&#xff0c;是查询语句模板&#xff0c;视图本身没有数据&#xff0c;在数据库中只保存了视图的定义…

[附源码]java毕业设计图书管理系统论文

项目运行 环境配置&#xff1a; Jdk1.8 Tomcat7.0 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术&#xff1a; SSM mybatis Maven Vue 等等组成&#xff0c;B/S模式 M…

Unity界面介绍:场景视图

场景视图是创建游戏的主要场所。用户将使用场景视图来选择和定位环境物体&#xff0c;角色物体&#xff0c;摄像机&#xff0c;敌人角色等其它的游戏物体。熟悉和操作场景视图中的物体是创建游戏中的重要步骤。为此&#xff0c;Unity也提供了一些快捷键来提高操作效率。 场景视…

UVM实战笔记(六)

第六章. UVM中的sequence 6.1 sequence基础 6.1.1 从driver中剥离激励产生功能 sequence机制的作用是为了从driver中剥离出产生激励的功能。在不同的测试用例中&#xff0c;将不同的sequence设置成sequencer的main_phase的default_sequence。当sequencer执行到main_phase时&…

用cocos实现的立方体宣传查看页面

cocos进入3.x时代&#xff0c;我也努力跟进&#xff0c;实现了一个将页面映射到立方体上进行旋转查看的效果。 效果如下&#xff1a; 要点 为了这个效果&#xff0c;我主要实现了3个要点&#xff1a; 将页面准确映射到立方体上面&#xff0c;适配不同尺寸的手机屏幕。对页面…

C++初阶作业 Vector作业详解

作者&#xff1a;小萌新 专栏&#xff1a;C初阶作业 作者简介&#xff1a;大二学生 希望能和大家一起进步 本篇博客介绍&#xff1a;讲解vecotr学校布置的作业 弥补自己不足的知识点 Vector作业详解Vector的特性及使用题目一 迭代器失效编程一 只出现一次的数字编程二 杨辉三角…

aws eks 部署jupyterhub执行kubectl

资料 https://aws.amazon.com/cn/blogs/china/teach-you-how-to-handle-kubeflow-on-eks-2/https://hub.docker.com/r/jupyterhub/singleuser 在部署kubeflow的过程中意识到在jupyter中能够运行外部指令&#xff0c;如果在其中集成一个kubectl&#xff0c;就可以实现命令的重…

【PowerQuery】Excel 自动刷新PowerQuery连接

Excel集成的PowerQuery提供了数据的手动刷新功能之外,也提供了数据的自动刷新功能。需要注意的是,PowerQuery提供的自动刷新功能是针对连接的,也就是说在PowerQuery自动刷新功能不是全局刷新功能,而是针对连接本身提供。接下来我们来看一下如何实现PowerQuery连接的自动刷新…

封装vue插件并发布到npm详细步骤

前言 平常使用Vue开发时&#xff0c;一个项目中多个地方需要用到的相同组件通常我们会封装为一个公共组件&#xff0c;但是如果项目不同我们也需要这个组件&#xff0c;那就需要复制一份公共组件代码到新项目&#xff0c;一个还好&#xff0c;如果是多个组件&#xff0c;这样就…

Design Compiler工具学习笔记(2)

目录 引言 知识储备 设计 objects 库 objects 命令 对象和属性 实际操作 all_* all_inputs all_outputs all_registers 其他 remove_from_collection list 数组 查看环境变量 设置/取消环境变量 引言 本篇继续学习 DC的基本使用。本篇主要学习 design 和 libr…

spring authorization server 0.3.1 - 默认示例

spring authorization server 0.3.1 - 默认oidc开始1、default-authorizationserver项目1.1、AuthorizationServerConfig.java1.2、DefaultSecurityConfig.java1.3、Jwks.java1.4、KeyGeneratorUtils.java1.5、DefaultAuthorizationServer.java1.6、application.yml2、client项…