Spring源码解析和扩展

流程梳理核心组件

在这里插入图片描述

BeanDefinitionReader

用来读取解析文件生成BeanDefinition的接口,除了xml文件可自定义各种规范如json文件解析成BeanDefinition

BeanDefinition

BeanDefinition是一个接口,它定义了一个bean的描述。一个BeanDefinition包含一个bean的名称、属性和构造函数的参数值等信息。
具体实现BeanDefinition接口的类还可以提供更多的信息,例如bean的类型、作用域、初始化方法等

BeanFactoryPostProcessor

增强修改BeanDenifition,(比如xml里的${jdbc.url}等占位符值的替换)

BeanPostProcessor

增强bean信息

Aware

对创建的bean进行操作的时候,如果需要其他对象,可以实现aware接口满足需要

Environment

访问和检索配置信息,将配置信息存储在各种属性源中,例如属性文件、环境变量、命令行参数等
StandardEnvironment->(System.getenv()System.getProperties())

例子
application.properties

a.b=good
@Autowired
private Environment environment;

//使用
String property = environment.getProperty("a.b");
System.out.println(property);

FactoryBean

接口三个方法
getObject();
Class<?> getObjectType();
boolean isSingleton();
BeanFactory生成bean要遵循spring完整的创建过程,由 spring 管理
FactoryBean是自己定义的创建bean的方式,只需要通过getObject方法即可

启动核心方法refresh方法

@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			/**
			 * 做刷新容器前的准备
			 * 1.设置容器启动时间
			 * 2.设置活跃状态true,关闭状态false
			 * 3.获取Environment对象并加载当前系统的系统属性值到Environment对象中
			 * 4.准备监听器和事件的对象,默认为空的集合
			 */
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			/**
			 * 创建容器对象DefaultListableBeanFactory
			 * 加载xml配置文件的属性到当前工厂中,最重要的就是BeanDenifition
			 */
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			/**
			 * beanFactory准备工作,填充各种属性
			 */
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				/**
				 * 空方法,子类覆盖方法做额外处理,此处一般不做任何扩展操作,可以看web中的代码是有实现的
				 */
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				/**
				 * 调用执行各种BeanFactoryPostProcessor,里面会调用beanFactory.getBean()找到自定义beanFactoryPostProcessor
				 * BeanFactoryPostProcessor接口的postProcessBeanFactory方法
				 * BeanFactoryPostProcessor增强修改BeanDenifition
				 * springboot自动装配@import使用子类ConfigruationClassPostProcessor
				 */
				invokeBeanFactoryPostProcessors(beanFactory);

				/**
				 * 注册BeanPostProcessor
				 * 里面会调用beanFactory.getBean()找到自定义beanPostProcessor
				 */
				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				/**
				 * 初始化信息源,和国际化相关.
				 * 调用beanFactory.registerSingleton()注册完整的messageSource对象到一级缓存
				 */
				// Initialize message source for this context.
				initMessageSource();

				/**
				 * 初始化容器事件传播器.
				 * beanFactory.registerSingleton()注册进去applicationEventMulticaster
				 */
				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				/**
				 * 空方法
				 */
				onRefresh();

				/**
				 * 为事件传播器注册事件监听器.
				 * 这个和上两个方法与ioc没关系
				 */
				// 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();
			}
		}
	}

解析

创建 bean的过程

通过 refresh方法的

// Instantiate all remaining (non-lazy-init) singletons.
				/**
				 * 初始化剩下的单实例(非懒加载的)
				 */
finishBeanFactoryInitialization(beanFactory);

执行创建剩下的单实例
可以看做调用链条

getBean()->doGetBean()->createBean()->doCreateBean()->createBeanInstance()->populateBean()

getBean:是BeanFactory的方法
doGetBean:实际干活的方法
createBean:创建bean
doCreateBean:实际干活的方法
createBeanInstance:反射实例化创建bean
populateBean:对实例属性赋值,循环依赖走这里循环调用到getBean方法

实例化bean后的流程
在这里插入图片描述

1.createBeanInstance实例化,开辟堆内存空间
2.属性赋值populateBean
3.判断是否实现了Aware接口,容器对象属性设置invokeAwareMethods(到这里实际上对象初始化完成了,下面流程进行增强)
4.调用beanPostProcessor的前置before方法
5.调用初始化方法invokeInitMethods ->判断如果实现InitializingBean就执行afterPropertiesSet,否则直接执行initMethod即可
6.调用beanPostProcessor的后置after方法,创建代理aop对象是这里,
从earlyProxyReferences缓存判断key(getEarlyBeanReference方法放进去的)无循环依赖就走这里创建aop对象,不然走getEarlyBeanReference方法
7.完整对象

三级缓存

在这里插入图片描述

DefaultSingletonBeanRegistry

/** 1级缓存Cache of singleton objects: bean name to bean instance. */
	private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);

	/** 3级缓存Cache of singleton factories: bean name to ObjectFactory. */
	private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);

	/** 2级缓存Cache of early singleton objects: bean name to bean instance. */
	private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);

循环依赖

现有A,B两个类,A有属性b,B有属性a
从上面说的refresh方法开始执行到

/**
				 * 初始化剩下的单实例(非懒加载的)
				 */
				finishBeanFactoryInitialization(beanFactory);
				

->beanFactory.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.
		/**
		 * 将所有的beanDefinition名字创建一个集合
		 */
		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()) {
				/**
				 * 如果是自定义的factoryBean
				 */
				if (isFactoryBean(beanName)) {
					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) {
							getBean(beanName);
						}
					}
				}
				else {
					/**
					 * 第一步getBean,不是自己定义FactoryBean就走这里由spring完整规范创建bean
					 */
					getBean(beanName);
				}
			}
		}

		// Trigger post-initialization callback for all applicable beans...
		for (String beanName : beanNames) {
			Object singletonInstance = getSingleton(beanName);
			if (singletonInstance instanceof SmartInitializingSingleton) {
				SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
				if (System.getSecurityManager() != null) {
					AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
						smartSingleton.afterSingletonsInstantiated();
						return null;
					}, getAccessControlContext());
				}
				else {
					smartSingleton.afterSingletonsInstantiated();
				}
			}
		}
	}

getBean(beanName);->

@Override
	public Object getBean(String name) throws BeansException {
		return doGetBean(name, null, null, false);
	}
protected <T> T doGetBean(
			String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
			throws BeansException {

		String beanName = transformedBeanName(name);
		Object bean;

		// Eagerly check singleton cache for manually registered singletons.
		/**
		 * 循环依赖的时候b创建好赋值a的时候,从这里拿到三级缓存的a
		 * 并把a放到二级缓存
		 */
		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 {
				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()) {
					/**
					 * getSingleton最后调用addSingleton把b放到一级缓存
					 * 同理 a创建完成也是放到一级缓存
					 */
					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();
					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 {
						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;
	}

createBean(beanName, mbd, args)->Object beanInstance = doCreateBean(beanName, mbdToUse, args);

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
			throws BeanCreationException {

		// Instantiate the bean.
		BeanWrapper instanceWrapper = null;
		if (mbd.isSingleton()) {
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
			/**
			 * 步骤createBeanInstance,反射实例化
			 */
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		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 {
					/**
					 * auowried自动注入,从这里进去,拿到需要注入的信息
					 */
					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");
			}
			/**
			 * 加入三级缓存
			 * getEarlyBeanReference判断是要暴露原始对象还是代理对象,需要代理返回代理,没有就原始
			 * invokeAwareMethods如果实现aware就执行aware的接口方法
			 * AOP是这个方法里用到的beanPostProcessor的扩展实现
			 */
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
		}

		// Initialize the bean instance.
		Object exposedObject = bean;
		try {
			/**
			 * 步骤populateBean,填充属性
			 * autowired注入
			 */
			populateBean(beanName, mbd, instanceWrapper);
			/**
			 * initializeBean里面执行BeanPostProcessor的 before,after
			 */
			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 " +
								"'getBeanNamesForType' 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;
	}

populateBean方法赋值属性如果存在其他bean引用会调用到getBean()方法从头开始循环
上面的流程走完的路程是

先创建 A ->a创建好就放到三级缓存(删除二级缓存的a,反正也没有)-> 再给 A属性赋值,发现b是空 -> 就去创建 b,创建好把b放三级缓存  
-> 再给b属性赋值(getSigleton方法),先从一级缓存拿a,空就从二级缓存拿 a,空就从三级拿a,拿到之后,把 a放到二级缓存,删除三级缓存的a 
->  b完成创建成品 ->  addSigleton方法把b放到一级缓存,并清空二三级的b ->   a赋值完 b后面成为成品也执行addSigleton

这里的三级缓存是Map<String, ObjectFactory<?>>,存放的是ObjectFactory接口的lambda表达式getEarlyBeanReference,当循环依赖的时候存在AOP代理对象,就会执行到getEarlyBeanReference

/**
			 * 加入三级缓存
			 * getEarlyBeanReference判断是要暴露原始对象还是代理对象,需要代理返回代理,没有就原始,里面有个缓存this.earlyProxyReferences.put(cacheKey, bean);)
			 * invokeAwareMethods如果实现aware就执行aware的接口方法
			 * AOP是这个方法里用到的beanPostProcessor的扩展实现
			 */
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));

AOP原理

aop是ioc的扩展实现,实现BeanPostProcessor接口调用after方法创建代理对象
BeanPostProcessor->AOP->动态代理(JDK/CGLIB)

public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
		implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {

AbstractAutoProxyCreator实现了BeanPostProcessor
spring创建 AOP代理对象的地方有两个
1.在BeanPostProcessor接口的after方法里会创建代理对象

/**
			 * 步骤populateBean,填充属性
			 * autowired注入
			 */
			populateBean(beanName, mbd, instanceWrapper);
			/**
			 * initializeBean里面执行BeanPostProcessor的 before,after
			 * 在这里执行after方法由AbstractAutoProxyCreator创建代理对象
			 */
			exposedObject = initializeBean(beanName, exposedObject, mbd);

createBeanInstance方法之后,会把实例化的对象放入三级缓存,当存在循环依赖的AOP代理对象的时候,在getSingleton方法会执行到getEarlyBeanReference提前创建代理对象,并放进缓存,防止在initializeBean里面调用AbstractAutoProxyCreator的after方法重复创建,
这里依然是循环调用BeanPostProcessor

/**
			 * 加入三级缓存
			 * getEarlyBeanReference判断是要暴露原始对象还是代理对象,需要代理返回代理,没有就原始
			 * invokeAwareMethods如果实现aware就执行aware的接口方法
			 * AOP是这个方法里用到的beanPostProcessor的扩展实现
			 */
			addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
------------------

protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
		System.out.println("开始执行getEarlyBeanReference()方法,beanName="+beanName);
		Object exposedObject = bean;
		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			/**
			 * AOP
			 * AbstractAutoProxyCreator是BeanPostProcessor的子类实现
			 * 可以看看子类的createProxy,CGLIB/JDK
			 */
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
					SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
					exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
				}
			}
		}
		return exposedObject;
	}

@Autowired原理

通过AutowiredAnnotationBeanPostProcessor来实现

public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter
		implements MergedBeanDefinitionPostProcessor, PriorityOrdered, BeanFactoryAware {

AbstractAutowireCapableBeanFactory的doCreateBean会执行到

// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					/**
					 * auowried自动注入,从这里进去,拿到需要注入的信息
					 */
					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,填充属性
			 * autowired注入
			 */
			populateBean(beanName, mbd, instanceWrapper);
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}

进入applyMergedBeanDefinitionPostProcessors方法

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			/**
			 * AutowiredAnnotationBeanPostProcessor实现了MergedBeanDefinitionPostProcessor接口,
			 * 进而实现了接口中的postProcessMergedBeanDefinition方法
			 */
			if (bp instanceof MergedBeanDefinitionPostProcessor) {
				MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
				bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
			}
		}
	}

进入postProcessMergedBeanDefinition方法

	@Override
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
	    //获取有@Autowired注解的元数据
		InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
		metadata.checkConfigMembers(beanDefinition);
	}

最终checkedElements就是@Autowired注解的属性元素
在这里插入图片描述

然后在populateBean方法里

for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					// 开始真正autowried注入
					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;
				}
			}

进入postProcessProperties方法

@Override
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
	// 这里获取metadata是从缓存获取的
		InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
		try {
			/**
			 * 注入
			 */
			metadata.inject(bean, beanName, pvs);
		}
		catch (BeanCreationException ex) {
			throw ex;
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
		}
		return pvs;
	}

进入inject再进入element.inject(target, beanName, pvs);
是AutowiredAnnotationBeanPostProcessor实现的inject方法
真正赋值成功在这里

@Override
		protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
			Field field = (Field) this.member;
			Object value;
			if (this.cached) {
				value = resolvedCachedArgument(beanName, this.cachedFieldValue);
			}
			else {
				DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
				desc.setContainingClass(bean.getClass());
				Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
				Assert.state(beanFactory != null, "No BeanFactory available");
				TypeConverter typeConverter = beanFactory.getTypeConverter();
				try {
				// 获取需要注入的bean实例
				// value是最终调用到调用factory.getBean()方法得到需要注入的对象
				// 依然可看作是循环依赖
					value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
				}
				catch (BeansException ex) {
					throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
				}
				synchronized (this) {
					if (!this.cached) {
						if (value != null || this.required) {
							this.cachedFieldValue = desc;
							registerDependentBeans(beanName, autowiredBeanNames);
							if (autowiredBeanNames.size() == 1) {
								String autowiredBeanName = autowiredBeanNames.iterator().next();
								if (beanFactory.containsBean(autowiredBeanName) &&
										beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
									this.cachedFieldValue = new ShortcutDependencyDescriptor(
											desc, autowiredBeanName, field.getType());
								}
							}
						}
						else {
							this.cachedFieldValue = null;
						}
						this.cached = true;
					}
				}
			}
			if (value != null) {
				ReflectionUtils.makeAccessible(field);
				// 真正注入@Autowired注解标注的属性值
				field.set(bean, value);
			}
		}
	}

@Resource原理

和@Autowired大致相同,入口地方相同
AbstractAutowireCapableBeanFactory的doCreateBean会执行到

// Allow post-processors to modify the merged bean definition.
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {
				try {
					/**
					 * @Auowried自动注入,从这里进去,拿到需要注入的信息
					 * @Resource也从这里进去
					 */
					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,填充属性
			 * autowired注入
			 */
			populateBean(beanName, mbd, instanceWrapper);
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}

applyMergedBeanDefinitionPostProcessors进去

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			/**
			 * AutowiredAnnotationBeanPostProcessor实现了MergedBeanDefinitionPostProcessor接口,
			 * 进而实现了接口中的postProcessMergedBeanDefinition方法
			 *
			 *
			 * 当bp为CommonAnnotationBeanPostProcessor时,会进行@Resource的注入
			 * 当bp为AutowiredAnnotationBeanPostProcessor时,会进行@Autowired的注入
			 */
			if (bp instanceof MergedBeanDefinitionPostProcessor) {
				MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
				bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
			}
		}
	}

进入CommonAnnotationBeanPostProcessor 的 postProcessMergedBeanDefinition方法

@Override
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
	// 比Autowired多了个super的方法
		super.postProcessMergedBeanDefinition(beanDefinition, beanType, beanName);
		InjectionMetadata metadata = findResourceMetadata(beanName, beanType, null);
		metadata.checkConfigMembers(beanDefinition);
	}

然后在populateBean方法里

for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					// 开始真正autowried注入,AutowiredAnnotationBeanPostProcessor的实现方法postProcessProperties
					// 也是resource注入的地方,CommonAnnotationBeanPostProcessor的实现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;
				}
			}

进入CommonAnnotationBeanPostProcessor的实现postProcessProperties

@Override
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
		InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass(), pvs);
		try {
		// 注入
			metadata.inject(bean, beanName, pvs);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName, "Injection of resource dependencies failed", ex);
		}
		return pvs;
	}

在这里插入图片描述
最后进入

protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs)
				throws Throwable {

			if (this.isField) {
				Field field = (Field) this.member;
				ReflectionUtils.makeAccessible(field);
				// getResourceToInject最终会调用getBean创建好放入一级缓存
				// 依然可以看作循环依赖链
				field.set(target, getResourceToInject(target, requestingBeanName));
			}
			else {
				if (checkPropertySkipping(pvs)) {
					return;
				}
				try {
					Method method = (Method) this.member;
					ReflectionUtils.makeAccessible(method);
					method.invoke(target, getResourceToInject(target, requestingBeanName));
				}
				catch (InvocationTargetException ex) {
					throw ex.getTargetException();
				}
			}
		}

@PostConstruct原理

由CommonAnnotationBeanPostProcessor实现

/**
	 * Create a new CommonAnnotationBeanPostProcessor,
	 * with the init and destroy annotation types set to
	 * {@link javax.annotation.PostConstruct} and {@link javax.annotation.PreDestroy},
	 * respectively.
	 */
	public CommonAnnotationBeanPostProcessor() {
		setOrder(Ordered.LOWEST_PRECEDENCE - 3);
		setInitAnnotationType(PostConstruct.class);
		setDestroyAnnotationType(PreDestroy.class);
		ignoreResourceType("javax.xml.ws.WebServiceContext");
	}
			populateBean(beanName, mbd, instanceWrapper);
			/**
			 * initializeBean里面执行BeanPostProcessor的 before,after
			 * 这里执行了@PostConstruct方法
			 */
			exposedObject = initializeBean(beanName, exposedObject, mbd);

CommonAnnotationBeanPostProcessor的父类InitDestroyAnnotationBeanPostProcessor里的before方法里执行

@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
	// 这里进去
		LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
		try {
			metadata.invokeInitMethods(bean, beanName);
		}
		catch (InvocationTargetException ex) {
			throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
		}
		return bean;
	}
private LifecycleMetadata findLifecycleMetadata(Class<?> clazz) {
		if (this.lifecycleMetadataCache == null) {
			// Happens after deserialization, during destruction...
			return buildLifecycleMetadata(clazz);
		}
		// Quick check on the concurrent map first, with minimal locking.
		LifecycleMetadata metadata = this.lifecycleMetadataCache.get(clazz);
		if (metadata == null) {
			synchronized (this.lifecycleMetadataCache) {
				metadata = this.lifecycleMetadataCache.get(clazz);
				if (metadata == null) {
				// 这里进去
					metadata = buildLifecycleMetadata(clazz);
					this.lifecycleMetadataCache.put(clazz, metadata);
				}
				return metadata;
			}
		}
		return metadata;
	}

InitDestroyAnnotationBeanPostProcessor的buildLifecycleMetadata方法被调用

private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) {
		List<LifecycleElement> initMethods = new ArrayList<>();
		List<LifecycleElement> destroyMethods = new ArrayList<>();
		Class<?> targetClass = clazz;

		do {
			final List<LifecycleElement> currInitMethods = new ArrayList<>();
			final List<LifecycleElement> currDestroyMethods = new ArrayList<>();

            // method.isAnnotationPresent(this.initAnnotationType)
            // this.initAnnotationType的值是PostConstruct.class
            //扫描是否被@PostConstruct标注
			ReflectionUtils.doWithLocalMethods(targetClass, method -> {
				if (this.initAnnotationType != null && method.isAnnotationPresent(this.initAnnotationType)) {
					LifecycleElement element = new LifecycleElement(method);
					currInitMethods.add(element);
					if (logger.isTraceEnabled()) {
						logger.trace("Found init method on class [" + clazz.getName() + "]: " + method);
					}
				}
				if (this.destroyAnnotationType != null && method.isAnnotationPresent(this.destroyAnnotationType)) {
					currDestroyMethods.add(new LifecycleElement(method));
					if (logger.isTraceEnabled()) {
						logger.trace("Found destroy method on class [" + clazz.getName() + "]: " + method);
					}
				}
			});

			initMethods.addAll(0, currInitMethods);
			destroyMethods.addAll(currDestroyMethods);
			targetClass = targetClass.getSuperclass();
		}
		while (targetClass != null && targetClass != Object.class);

		return new LifecycleMetadata(clazz, initMethods, destroyMethods);
	}

在这里插入图片描述
在这里插入图片描述
比initizingBean接口的afterPropertiesSet方法先一步

ConfigurationClassPostProcessor扫描装配@Configuration,@ComponentScan,@Component,@Import,@Bean等

在这里插入图片描述
ConfigurationClassPostProcessor属于BeanFactoryPostProcessor,BeanFactoryPostProcessor通常用来增强修改BeanDefinition
也是BeanDefinitionRegistryPostProcessor类型,能向spring注册BeanDefinition
在这里插入图片描述
先执行postProcessBeanDefinitionRegistry,然后执行postProcessBeanFactory
入口refresh方法里的invokeBeanFactoryPostProcessors(beanFactory);方法

/**
* 调用执行各种BeanFactoryPostProcessor,里面会调用beanFactory.getBean()找到自定义beanFactoryPostProcessor
* BeanFactoryPostProcessor接口的postProcessBeanFactory方法
* BeanFactoryPostProcessor增强修改BeanDenifition
* springboot自动装配@import
* 扫描注解标注需要加入容器的bean信息到beanDenifition,比如@Componment
*/
invokeBeanFactoryPostProcessors(beanFactory);

然后PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors()进去

...省略
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
                // 类型匹配进去
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
							//首先执行上面的postProcessBeanDefinitionRegistry()
										registryProcessor.postProcessBeanDefinitionRegistry(registry);
					registryProcessors.add(registryProcessor);
				}
				else {
					regularPostProcessors.add(postProcessor);
				}
			}
...省略

然后进入ConfigurationClassPostProcessor的processConfigBeanDefinitions(registry);

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
		List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
		String[] candidateNames = registry.getBeanDefinitionNames();

		for (String beanName : candidateNames) {
			BeanDefinition beanDef = registry.getBeanDefinition(beanName);
			if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
					ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
				}
			}
			/**
			 * 判断是否是配置类,如果是@Configuration为BeanDefinition设置属性为ful
			 * @Bean,@Component,@ComponentScan,@Import,@ImportResource这些注解为lite
			 */
			else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
				configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
			}
		}

		// Return immediately if no @Configuration classes were found
		if (configCandidates.isEmpty()) {
			return;
		}

		// Sort by previously determined @Order value, if applicable
		configCandidates.sort((bd1, bd2) -> {
			int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
			int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
			return Integer.compare(i1, i2);
		});

		// Detect any custom bean name generation strategy supplied through the enclosing application context
		SingletonBeanRegistry sbr = null;
		if (registry instanceof SingletonBeanRegistry) {
			sbr = (SingletonBeanRegistry) registry;
			if (!this.localBeanNameGeneratorSet) {
				BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
				if (generator != null) {
					this.componentScanBeanNameGenerator = generator;
					this.importBeanNameGenerator = generator;
				}
			}
		}

		if (this.environment == null) {
			this.environment = new StandardEnvironment();
		}

		// Parse each @Configuration class
		ConfigurationClassParser parser = new ConfigurationClassParser(
				this.metadataReaderFactory, this.problemReporter, this.environment,
				this.resourceLoader, this.componentScanBeanNameGenerator, registry);

		Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
		Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
		do {
			/**
			 * @Configuration注解以及通过@ComponentScan注解扫描的类加入到BeanDefinitionMap中,其他的
			 * 的比如这里用到的类《引入的新类》@import等不会直接加入到BeanDefinitionMap中,而是包含所有注解的一起存到parser的configurationClasses属性,
			 * 后面用到
			 */
			parser.parse(candidates);
			parser.validate();

			/**
			 * 上面parser.parse(candidates)方法解析后的类信息放到了parser.getConfigurationClasses()
 			 */
			Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
			configClasses.removeAll(alreadyParsed);

			// Read the model and create bean definitions based on its content
			if (this.reader == null) {
				this.reader = new ConfigurationClassBeanDefinitionReader(
						registry, this.sourceExtractor, this.resourceLoader, this.environment,
						this.importBeanNameGenerator, parser.getImportRegistry());
			}
			/**
			 * 上面一步parser.parse(candidates)方法实际上加载了一部分BeanDefinition了
			 * 但是上面用到的类可能用如@Import,@Bean引入其他类,这里进一步解析这些类到BeanDefinition
			 */
			this.reader.loadBeanDefinitions(configClasses);//加载BeanDefinitions
			alreadyParsed.addAll(configClasses);

			candidates.clear();
			/**
			 * 上面实际上都解析完成了,这里的判断好像没啥意义
			 */
			if (registry.getBeanDefinitionCount() > candidateNames.length) {
				String[] newCandidateNames = registry.getBeanDefinitionNames();
				Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
				Set<String> alreadyParsedClasses = new HashSet<>();
				for (ConfigurationClass configurationClass : alreadyParsed) {
					alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
				}
				for (String candidateName : newCandidateNames) {
					if (!oldCandidateNames.contains(candidateName)) {
						BeanDefinition bd = registry.getBeanDefinition(candidateName);
						if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
								!alreadyParsedClasses.contains(bd.getBeanClassName())) {
							candidates.add(new BeanDefinitionHolder(bd, candidateName));
						}
					}
				}
				candidateNames = newCandidateNames;
			}
		}
		while (!candidates.isEmpty());

		// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
		if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
			sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
		}

		if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
			// Clear cache in externally provided MetadataReaderFactory; this is a no-op
			// for a shared cache since it'll be cleared by the ApplicationContext.
			((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
		}
	}

parser.parse(candidates);进去

public void parse(Set<BeanDefinitionHolder> configCandidates) {
		for (BeanDefinitionHolder holder : configCandidates) {
			BeanDefinition bd = holder.getBeanDefinition();
			try {
				if (bd instanceof AnnotatedBeanDefinition) {
					// 会扫描到@Configuration,@ComponentScan,@Component,@Import引入的所有的需要的类
					// 标注注解扫描注册的bean会在这里解析完成放到configurationClasses保存起来,后面会用到
					// 进去
					parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
				}
				else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
					parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
				}
				else {
					parse(bd.getBeanClassName(), holder.getBeanName());
				}
			}
			catch (BeanDefinitionStoreException ex) {
				throw ex;
			}
			catch (Throwable ex) {
				throw new BeanDefinitionStoreException(
						"Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
			}
		}

		this.deferredImportSelectorHandler.process();
	}
protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
...省略
		// Recursively process the configuration class and its superclass hierarchy.
		// 循环所有父类
		SourceClass sourceClass = asSourceClass(configClass);
		do {
		// 核心处理
			sourceClass = doProcessConfigurationClass(configClass, sourceClass);
		}
		while (sourceClass != null);

		this.configurationClasses.put(configClass, configClass);
	}
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
			throws IOException {

		if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
			// Recursively process any member (nested) classes first
			//递归处理内部类
			processMemberClasses(configClass, sourceClass);
		}

		// Process any @PropertySource annotations
		for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
				sourceClass.getMetadata(), PropertySources.class,
				org.springframework.context.annotation.PropertySource.class)) {
			if (this.environment instanceof ConfigurableEnvironment) {
				processPropertySource(propertySource);
			}
			else {
				logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
						"]. Reason: Environment must implement ConfigurableEnvironment");
			}
		}

		// Process any @ComponentScan annotations
		/**
		 *扫描出ComponentScans, ComponentScan注解的所有属性比如basePackages的值
		 */
		Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
				sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
		if (!componentScans.isEmpty() &&
				!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
			for (AnnotationAttributes componentScan : componentScans) {
				// The config class is annotated with @ComponentScan -> perform the scan immediately
				/**
				 * 装载basePackages指定的包类到BeanDefinition
				 */
				Set<BeanDefinitionHolder> scannedBeanDefinitions =
						this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
				// Check the set of scanned definitions for any further config classes and parse recursively if needed
				for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
					/**
					 * 子类如果还有ComponentScans,ComponentScan
					 * 最后再次循环调用checkConfigurationClassCandidate 和 parse方法
					 */
					BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
					if (bdCand == null) {
						bdCand = holder.getBeanDefinition();
					}
					if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
						parse(bdCand.getBeanClassName(), holder.getBeanName());
					}
				}
			}
		}

		/**
		 * 处理Import注解注册的bean不会放到BeanDefinition,而是configurationClass属性
		 * springboot用到的的@Import,processImports这个方法会递归调用到自己如果@import的类存在继续引入其他类
		 */
		// Process any @Import annotations
		processImports(configClass, sourceClass, getImports(sourceClass), true);

		/**
		 * 处理处理 @ImportResource解析配置文件的bean
		 */
		// Process any @ImportResource annotations
		AnnotationAttributes importResource =
				AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
		if (importResource != null) {
			String[] resources = importResource.getStringArray("locations");
			Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
			for (String resource : resources) {
				String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
				configClass.addImportedResource(resolvedResource, readerClass);
			}
		}

		/**
		 * 处理 @Bean
		 */
		// Process individual @Bean methods
		Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
		for (MethodMetadata methodMetadata : beanMethods) {
			configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
		}
	...省略

postProcessBeanFactory方法 CGLIB代理被@Configuration注解标注的类

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		int factoryId = System.identityHashCode(beanFactory);
		
        // 如果还没执行解析工作,则先去执行processConfigBeanDefinitions进行解析
		this.factoriesPostProcessed.add(factoryId);
		if (!this.registriesPostProcessed.contains(factoryId)) {
			processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory);
		}
		// 对当前容器中被@Configuration注解标注的BeanDefinition进行CGLIb增强
		enhanceConfigurationClasses(beanFactory);
		beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory));
	}

代理@Configuration注解标注的类是为了保证单例的问题

@Configuration
public class MyConfiguration {
    @Bean
    public A a() {
        return new A();
    }

    @Bean
    public B b() {
        a();// 无法保证单例
        return new B();
    }
}

Springboot自动装配原理

@SpringBootConfiguration

本质就是@Configuration

@EnableAutoConfiguration

@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
AutoConfigurationImportSelector实现了ImportSelector
会执行到下面的方法
 public String[] selectImports(AnnotationMetadata annotationMetadata) {
        if (!this.isEnabled(annotationMetadata)) {
            return NO_IMPORTS;
        } else {
            AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
            // 进入里面最后会调用到List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
            AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
            return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
        }
    }
里面会调用到
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
        MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);
        if (result != null) {
            return result;
        } else {
            try {
            //从类路径的META-INF/spring.factories中加载所有默认的自动配置类
            //筛选出EnableAutoConfiguration对应的配置类注册为bean
                Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
                LinkedMultiValueMap result = new LinkedMultiValueMap();

                while(urls.hasMoreElements()) {
                    URL url = (URL)urls.nextElement();
                    UrlResource resource = new UrlResource(url);
                    Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                    Iterator var6 = properties.entrySet().iterator();

                    while(var6.hasNext()) {
                        Entry<?, ?> entry = (Entry)var6.next();
                        String factoryTypeName = ((String)entry.getKey()).trim();
                        String[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
                        int var10 = var9.length;

                        for(int var11 = 0; var11 < var10; ++var11) {
                            String factoryImplementationName = var9[var11];
                            result.add(factoryTypeName, factoryImplementationName.trim());
                        }
                    }
                }

                cache.put(classLoader, result);
                return result;
            } catch (IOException var13) {
                throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13);
            }
        }
    }

在这里插入图片描述

@ComponentScan

查看上面的 ConfigurationClassPostProcessor扫描装配 解析原理

springboot启动自动装配步骤

1、当启动springboot应用程序的时候,会先创建SpringApplication的对象,在对象的构造方法中会进行某些参数的初始化工作,
最主要的是判断当前应用程序的类型以及初始化器和监听器,在这个过程中会加载整个应用程序中的spring.factories文件,将文件的内容放到缓存对象中,方便后续获取。

2SpringApplication对象创建完成之后,开始执行run方法,来完成整个启动,
启动过程中最主要的有两个方法,第一个叫做prepareContext,第二个叫做refreshContext,在这两个关键步骤中完整了自动装配的核心功能,
前面的处理逻辑包含了上下文对象的创建,banner的打印,异常报告期的准备等各个准备工作,方便后续来进行调用。

3、在prepareContext方法中主要完成的是对上下文对象的初始化操作,包括了属性值的设置,
比如环境对象,在整个过程中有一个非常重要的方法,叫做load,load主要完成一件事,
将当前启动类做为一个beanDefinition注册到registry中,方便后续在进行BeanFactoryPostProcessor调用执行的时候,
找到对应的主类,来完成@SpringBootApplicaiton,@EnableAutoConfiguration等注解的解析工作

4、在refreshContext方法中会进行整个容器刷新过程,会调用中spring中的refresh方法,refresh中有13个非常关键的方法,来完成整个spring应用程序的启动,在自动装配过程中,
会调用invokeBeanFactoryPostProcessor方法,在此方法中主要是对ConfigurationClassPostProcessor类的处理,这次是BFPP的子类也是BDRPP的子类,
在调用的时候会先调用BDRPP中的postProcessBeanDefinitionRegistry方法,
然后调用postProcessBeanFactory方法,在执行postProcesseanDefinitionRegistry的时候回解析处理各种注解,
包含@PropertySource,@ComponentScan,@ComponentScans@Bean,@Import等注解,最主要的是@Import注解的解析

5<查看上面的 ConfigurationClassPostProcessor扫描装配 解析原理>
在解析@Import注解的时候,会有一个getimports的方法,从主类开始递归解析注解,把所有包含@Import的注解都解析到,
然后在processlmport方法中对Import的类进行分类,此处主要识别的时候AutoConfigurationImportSelect归属于ImportSelect的子类,
在后续过程中会调用deferredImportSelectorHandler中的process方法,来完整EnableAutoConfiguration的期薪

首先进入run

public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
        return (new SpringApplication(primarySources)).run(args);
    }
//SpringApplication
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
        this.sources = new LinkedHashSet();
        this.bannerMode = Mode.CONSOLE;
        this.logStartupInfo = true;
        this.addCommandLineProperties = true;
        this.addConversionService = true;
        this.headless = true;
        this.registerShutdownHook = true;
        this.additionalProfiles = new HashSet();
        this.isCustomEnvironment = false;
        this.lazyInitialization = false;
        this.resourceLoader = resourceLoader;
        Assert.notNull(primarySources, "PrimarySources must not be null");
        this.primarySources = new LinkedHashSet(Arrays.asList(primarySources));
        this.webApplicationType = WebApplicationType.deduceFromClasspath();
        //设置了initializers和listeners,
        //initializers和listeners来源于spring.factories中定义的ApplicationContextInitializer和ApplicationListener
        this.setInitializers(this.getSpringFactoriesInstances(ApplicationContextInitializer.class));
        this.setListeners(this.getSpringFactoriesInstances(ApplicationListener.class));
        this.mainApplicationClass = this.deduceMainApplicationClass();
    }

run方法里

 public ConfigurableApplicationContext run(String... args) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
        this.configureHeadlessProperty();
        SpringApplicationRunListeners listeners = this.getRunListeners(args);
        listeners.starting();

        Collection exceptionReporters;
        try {
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
            ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
            this.configureIgnoreBeanInfo(environment);
            //打印springboot图案
            Banner printedBanner = this.printBanner(environment);
            // 创建上下文默认的服务类型是SERVLET,所以创建的是**”注解配置的Servlet-Web服务容器“,即AnnotationConfigServletWebServerApplicationContext
            //创建DeafualtListsbleBeanFactory
            //创建this.reader = new AnnotatedBeanDefinitionReader(this);
            //创建this.scanner = new ClassPathBeanDefinitionScanner(this);
            context = this.createApplicationContext();
            exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
            //prepareContext方法
            //对上下文content设置环境对象
            
            this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
            //refreshContext方法
            // 调用到spring的refresh()入口方法
            this.refreshContext(context);
            this.afterRefresh(context, applicationArguments);
            stopWatch.stop();
            if (this.logStartupInfo) {
                (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
            }

            listeners.started(context);
            this.callRunners(context, applicationArguments);
        } catch (Throwable var10) {
            this.handleRunFailure(context, var10, exceptionReporters, listeners);
            throw new IllegalStateException(var10);
        }

        try {
            listeners.running(context);
            return context;
        } catch (Throwable var9) {
            this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
            throw new IllegalStateException(var9);
        }
    }

常用扩展

1.对 Aware接口扩展获取容器对象

对创建的bean进行操作的时候,如果需要其他对象,可以实现aware接口满足需要
实现想要的Aware接口,重写对应的set方法,这样可以获取想要的其他对象

public class TestAware implements ApplicationContextAware, BeanFactoryAware {

	private ApplicationContext applicationContext;
	private BeanFactory beanFactory;

	public BeanFactory getBeanFactory() {
		return beanFactory;
	}

	private String name;
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		System.out.println("通过aware接口设置applicationContext");
		this.applicationContext=applicationContext;
	}

	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory=beanFactory;
	}
    
    public void test(){
    	Object o=this.beanFactory.getbBean("beanName");
    	Object o2=this.applicationContext.getbBean("beanName");
	}
}

2.全局异常捕获

这样可以放心写自己的业务代码,在这里统一捕获

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        // 判断不同异常进行对应处理
        retur null;
    }
}

3.自定义拦截器

public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
            
        //业务逻辑
        return true;
    }
}

注册拦截器

@Configuration
public class MyWebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor());
    }
}

4.类型转换器

Converter<S,T>:将 S 类型对象转为 T 类型对象

@Configuration
public class MyWebConfig implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
    	//Converter将String转化成LocalDateTime
        registry.addConverter(new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(String s) {
                TemporalAccessor yyyyMMdd = DateTimeFormatter.ofPattern("yyyyMMddHH:mm:ss").parse(s);
                return LocalDateTime.from(yyyyMMdd);
            }
        });
    }
}

请求后自动转换
http://127.0.0.1:8080/t/test?localDateTime=2023111112:00:00&t=123

@RequestMapping("/t")
@RestController
public class TestController {
    @GetMapping("/test")
    public Object test(LocalDateTime localDateTime,String t){
        System.out.println(localDateTime);
        System.out.println(t);
        return localDateTime+t;
    }
}

5.导入配置@Import

public class T {
}@Import引入的类会被实例化bean对象加入到spring容器
@Import({T.class})
@Configuration
public class MyConfig {
}

其他地方可以直接注入拿来用
@RequestMapping("/t")
@RestController
public class TestController {

    @Autowired
    private T t;
}

关联性

public class T2 {
}

@Import({T2.class})
public class T {
}

@Import({T.class})
@Configuration
public class MyConfig {
}

具有关联性,把@Import@ImportResource@PropertySource等注解引入的类进行递归,一次性全部引入
@Autowired
private T t;

@Autowired
private T2 t2;

结合ImportSelector
实现ImportSelector接口

public class MyImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        return new String[]{"com.example.spboottest.config.T3"};
    }
}

引入MyImportSelector,一次性引入数组多个类
@Import({T.class,MyImportSelector.class})
@Configuration
public class MyConfig {
}

结合ImportBeanDefinitionRegistrar
实现ImportBeanDefinitionRegistrar接口
写架子的时候方法很多,可以自定义BeanDefinition手动注入到spring容器

// 自己定义BeanDefinition注入到spring容器更灵活
public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
 @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(T4.class);
        beanDefinitionBuilder.addPropertyValue("name","张三");
        registry.registerBeanDefinition("t4",beanDefinitionBuilder.getBeanDefinition());
    }
    }
}

//引入T4
@Import({T.class,MyImportSelector.class,MyImportBeanDefinitionRegistrar.class})
@Configuration
public class MyConfig {
}

6.项目启动时

初始化操作,比如加载缓存数据等等

@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("===============START==============");
    }
}

7.BeanFactoryPostProcessor增强修改BeanDefinition

BeanDefinition是用来记录需要实例化的bean的定义信息,可以修改

@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		BeanDefinition beanDefinition = beanFactory.getBeanDefinition("a");
// 修改beanDefinition属性,
//		beanDefinition.setXXX
		System.out.println("设置BeanDefinition:"+beanDefinition);
	}
}

8.BeanPostProcessor增强修改Bean

1.createBeanInstance实例化,开辟堆内存空间
2.属性赋值populateBean
3.判断是否实现了Aware接口,容器对象属性设置invokeAwareMethods(到这里实际上对象初始化完成了,下面流程进行增强)
4.调用beanPostProcessor的前置before方法
5.调用初始化方法invokeInitMethods ->判断如果实现InitializingBean就执行afterPropertiesSet,否则直接执行initMethod即可
6.调用beanPostProcessor的后置after方法,创建代理aop对象是这里,
从earlyProxyReferences缓存判断key(getEarlyBeanReference方法放进去的)无循环依赖就走这里创建aop对象,不然走getEarlyBeanReference方法
7.完整对象

在第4和第6步执行

@Component
public class MyBeanPostProcessor implements  BeanPostProcessor {
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("我的beanPostProcessor的befor:"+beanName+"  "+bean);
		// Bean实例化后,可以修改Bean
		return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		System.out.println("我的beanPostProcessor的after:"+beanName+"  "+bean);
		return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
	}
}

9.初始化方法

实现InitializingBean接口或者@PostConstruct
@PostConstruct会比InitializingBean先一步执行
分别是上面的4 和 5 步

@Component
public class InitTest implements InitializingBean {

//第 4 步
    @PostConstruct
    public void doPostConstruct(){
        System.out.println("PostConstruct执行了");
    }
//第 5 步
// 让bean创建好后最后给用户一次操作的机会
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet执行了");
    }
}

10.DisposableBean销毁

实现DisposableBean接口,并且重写它的destroy方法

@Component
public class MyDisposableBean implements DisposableBean {
    @Override
    public void destroy() throws Exception {
        System.out.println("MyDisposableBean销毁了");
    }
}

11.FactoryBean

BeanFactory创建bean要遵循spring完整流程创建
FactoryBean由用户自定义实现,更加灵活

public class MyFactoryBean implements FactoryBean<Person2> {
	@Override
	public Person2 getObject() throws Exception {
		/**
		 * 自己想怎么创建对象就创建对象,不需要经过标准的处理流程
		 */
		return new Person2();
	}

	@Override
	public Class<?> getObjectType() {
		return Person2.class;
	}
}
Person2 person2 = (Person2)ac.getBean("myFactoryBean");
System.out.println(person2);
  • 19
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring源码解析是指对Spring框架的源代码进行深入分析和解读的过程。Spring框架是一个开源的Java企业级应用程序框架,提供了高度灵活和可扩展的开发环境。 Spring框架的源代码解析涉及了众多的模块和组件,包括核心容器、AOP(面向切面编程)、数据访问、Web开发等。通过对这些模块和组件的源代码进行解析,我们可以更加深入地了解Spring框架的工作原理和设计思想。 Spring源码解析的好处在于,可以帮助我们更好地理解Spring框架的各种功能和特性,并且能够帮助开发人员更加高效地使用和定制Spring框架,解决实际项目开发中的问题。 在进行Spring源码解析时,我们可以关注一些关键的概念和类,比如BeanFactory、ApplicationContext、BeanPostProcessor、AOP代理等。这些核心类和概念是理解Spring框架工作机制的重要基础。 进行Spring源码解析时,我们可以使用一些常见的工具和方法,比如IDE(集成开发环境)的调试功能、查看和分析源代码的注释和文档、调试和运行项目的示例代码等。 通过Spring源码解析,我们可以学到很多有关软件开发的知识和经验,比如面向对象编程、设计模式、依赖注入、控制反转等。这些知识和经验对于我们提升自己的技术水平和解决实际项目中的问题都有很大的帮助。 总之,Spring源码解析是一项非常有价值的学习和研究工作,可以帮助我们更好地理解和应用Spring框架,提高自己的技术能力和软件开发水平。希望以上的回答能够满足您的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可——叹——落叶飘零

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值