SpringIOC源码学习笔记

在这里插入图片描述

ClassPathXmlApplicationContext//IOC容器创建

		源码:
		public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
			this(new String[] {configLocation}, true, null);
		}				
		//ClassPathXmlApplicationContext构造器
		2.public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException {
			super(parent);
			setConfigLocations(configLocations);
			if (refresh) {
				refresh();
			}
		}

refresh()

			源码:
			@Override
			3.public void refresh() throws BeansException, IllegalStateException {
				synchronized (this.startupShutdownMonitor) {
					// Prepare this context for refreshing.
					//容器准备刷新
					prepareRefresh();
					
					// Tell the subclass to refresh the internal bean factory.
					//Spring解析xml配置文件将要创建的所有bean的配置信息并保存起来,创建所有bean工厂,把xml配置文件里每一个bean配置解析读取保存起来,方便下一次使用
					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.
						//bean工厂的后置处理器
						postProcessBeanFactory(beanFactory);
						
						// Invoke factory processors registered as beans in the context.
						//执行bean工厂的后置处理器注册
						invokeBeanFactoryPostProcessors(beanFactory);
						
						// Register bean processors that intercept bean creation.
						//注册bean工厂的后置处理器(Spring自己的组件的后置处理器)
						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.
						//初始化所有单实例bean的地方
						finishBeanFactoryInitialization(beanFactory);

						finishRefresh();
					}
					catch (BeansException ex) {
						if (logger.isWarnEnabled()) {
							logger.warn("Exception encountered during context initialization - " +
									"cancelling refresh attempt: " + ex);
						}

						destroyBeans();

						cancelRefresh(ex);

						throw ex;
					}
					finally {
						resetCommonCaches();
					}
				}
			}

finishBeanFactoryInitialization(beanFactory)//初始化所有单实例bean的地方

					源码:
					4.protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
						// Initialize conversion service for this context.
						//初始化类型转换的组件服务,自定义类型转换
						if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
								beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
							beanFactory.setConversionService(
									beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
						}

						// Register a default embedded value resolver if no bean post-processor
						// (such as a PropertyPlaceholderConfigurer bean) registered any before:
						// at this point, primarily for resolution in annotation attribute values.
						if (!beanFactory.hasEmbeddedValueResolver()) {
							beanFactory.addEmbeddedValueResolver(new StringValueResolver() {
								@Override
								public String resolveStringValue(String strVal) {
									return getEnvironment().resolvePlaceholders(strVal);
								}
							});
						}

						// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
						//初始化加载时WeaverAware
						String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
						for (String weaverAwareName : weaverAwareNames) {
							getBean(weaverAwareName);
						}

						// Stop using the temporary ClassLoader for type matching.
						//设置临时的类加载器
						beanFactory.setTempClassLoader(null);

						// Allow for caching all bean definition metadata, not expecting further changes.
						//冻结配置,别人无法修改
						beanFactory.freezeConfiguration();

						// Instantiate all remaining (non-lazy-init) singletons.
						//预初始化所有单实例
						beanFactory.preInstantiateSingletons();
					}

preInstantiateSingletons()//预初始化所有单实例

								源码:
								@Override
								public void preInstantiateSingletons() throws BeansException {
									if (this.logger.isDebugEnabled()) {
										this.logger.debug("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<String>(this.beanDefinitionNames);

									// Trigger initialization of all non-lazy singleton beans...
									//按顺序创建bean
									for (String beanName : beanNames) {
										//根据beanId获取到bean的定义信息
										RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
										//判断bean是单实例的,并且不是抽象的,并且不是懒加载的
										if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
											//是否是一个实现了FactoryBean接口的bean
											if (isFactoryBean(beanName)) {
												final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
												boolean isEagerInit;
												if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
													isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
														@Override
														public Boolean run() {
															return ((SmartFactoryBean<?>) factory).isEagerInit();
														}
													}, getAccessControlContext());
												}
												else {
													isEagerInit = (factory instanceof SmartFactoryBean &&
															((SmartFactoryBean<?>) factory).isEagerInit());
												}
												if (isEagerInit) {
													getBean(beanName);
												}
											}
											else {
												//创建bean的细节对象
												getBean(beanName);
											}
										}
									}
								}

getBean(beanName)//创建bean的细节对象

									源码:
									public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {

										@Override
										public Object getBean(String name) throws BeansException {
											//创建bean的细节
											return doGetBean(name, null, null, false);
										}
									}

doGetBean()//创建bean的细节

										源码:
										@SuppressWarnings("unchecked")
										protected <T> T doGetBean(
												final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
												throws BeansException {
											
											//拿到bean名
											final String beanName = transformedBeanName(name);
											Object bean;

											// Eagerly check singleton cache for manually registered singletons.
											//先从已经注册的单实例bean缓存里有没有这个bean,第一次创建bean是没有的
											Object sharedInstance = getSingleton(beanName);
											if (sharedInstance != null && args == null) {
												if (logger.isDebugEnabled()) {
													if (isSingletonCurrentlyInCreation(beanName)) {
														logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
																"' that is not fully initialized yet - a consequence of a circular reference");
													}
													else {
														logger.debug("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 (args != null) {
														// Delegation to parent with explicit args.
														return (T) parentBeanFactory.getBean(nameToLookup, args);
													}
													else {
														// No args -> delegate to standard getBean method.
														return parentBeanFactory.getBean(nameToLookup, requiredType);
													}
												}
												//判断doGetBean(name, null, null, false),最后的参数
												if (!typeCheckOnly) {
													//标记bean已经创建了
													markBeanAsCreated(beanName);
												}

												try {
													//获取合并的本地bean信息,总是获取到当前bean的定义信息
													final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
													checkMergedBeanDefinition(mbd, beanName, args);

													// Guarantee initialization of beans that the current bean depends on.
													//拿到创建当前bean之前需要提前创建的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);
															getBean(dep);
														}
													}

													// Create bean instance.
													//如果DependsOn是单例的,创建bean实例
													if (mbd.isSingleton()) {
														sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
															@Override
															public Object getObject() throws BeansException {
																try {
																//bean的创建
																	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();
														final 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, new ObjectFactory<Object>() {
																@Override
																public Object getObject() throws BeansException {
																	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 && bean != null && !requiredType.isInstance(bean)) {
												try {
													return getTypeConverter().convertIfNecessary(bean, requiredType);
												}
												catch (TypeMismatchException ex) {
													if (logger.isDebugEnabled()) {
														logger.debug("Failed to convert bean '" + name + "' to required type '" +
																ClassUtils.getQualifiedName(requiredType) + "'", ex);
													}
													throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
												}
											}
											return (T) bean;
										}

getSingleton()//如果DependsOn是单例的,创建bean实例

											源码:
											public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
												Assert.notNull(beanName, "'beanName' must not be null");
												synchronized (this.singletonObjects) {
													//先从一个地方将一个将bean,get出来
													Object singletonObject = this.singletonObjects.get(beanName);
													if (singletonObject == null) {
														if (this.singletonsCurrentlyInDestruction) {
															throw new BeanCreationNotAllowedException(beanName,
																	"Singleton bean creation not allowed while singletons of this factory are in destruction " +
																	"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
														}
														if (logger.isDebugEnabled()) {
															logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
														}
														//创建bean之前
														beforeSingletonCreation(beanName);
														boolean newSingleton = false;
														boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
														if (recordSuppressedExceptions) {
															this.suppressedExceptions = new LinkedHashSet<Exception>();
														}
														try {
															//利用反射,bean创建
															singletonObject = singletonFactory.getObject();
															newSingleton = true;
														}
														catch (IllegalStateException ex) {
															// Has the singleton object implicitly appeared in the meantime ->
															// if yes, proceed with it since the exception indicates that state.
															singletonObject = this.singletonObjects.get(beanName);
															if (singletonObject == null) {
																throw ex;
															}
														}
														catch (BeanCreationException ex) {
															if (recordSuppressedExceptions) {
																for (Exception suppressedException : this.suppressedExceptions) {
																	ex.addRelatedCause(suppressedException);
																}
															}
															throw ex;
														}
														finally {
															if (recordSuppressedExceptions) {
																this.suppressedExceptions = null;
															}
															afterSingletonCreation(beanName);
														}
														if (newSingleton) {
															//添加创建的bean,单实例
															addSingleton(beanName, singletonObject);
														}
													}
													return (singletonObject != NULL_OBJECT ? singletonObject : null);
												}
											}

singletonObjects()//先从一个地方将一个将bean,get出来

												源码:
												//IOC容器之一:保存单实例bean的地方
												public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
													//缓存所有单实例的对象,按照对象的名字创建对象的实例
													/** Cache of singleton objects: bean name --> bean instance */
													private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);
												}

addSingleton()//添加创建的bean,单实例

												源码:
												protected void addSingleton(String beanName, Object singletonObject) {
													synchronized (this.singletonObjects) {
														//将创建好的bean对象加入保存到singletonObjects,Map中
														this.singletonObjects.put(beanName, (singletonObject != null ? singletonObject : NULL_OBJECT));
														this.singletonFactories.remove(beanName);
														this.earlySingletonObjects.remove(beanName);
														this.registeredSingletons.add(beanName);
													}
												}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值