【框架专题】管理型容器——SpringIOC源码——整体流程

SpringIOC源码——外部流程与结构

public void refresh() throws BeansException, IllegalStateException {
     
		synchronized (this.startupShutdownMonitor) {
     
			prepareRefresh();//准备一些早期事件和早期监听器以及容器状态的初始化
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();//返回一个bean工厂,用户可以定制自己的工厂或者用默认的
			prepareBeanFactory(beanFactory);//
			try {
      
				postProcessBeanFactory(beanFactory);//工厂配置一些基本组件和利用工厂注册一些早期需要的东西
				invokeBeanFactoryPostProcessors(beanFactory);//调用工厂后置处理,实现工厂内部组件的定制,spring有三个内置的工厂后置处理,稍后讲
				registerBeanPostProcessors(beanFactory);//实例化所有实现了后置处理器的bean
				initMessageSource();//国际化
				initApplicationEventMulticaster();//初始化事件一些派发
				onRefresh();//子类实现
				registerListeners();//注册监听器
				/*
				  @重点,开始工厂的工作流程
                 */
				finishBeanFactoryInitialization(beanFactory);
				finishRefresh();
			}

			catch (BeansException ex) {
     
			   ……
			}

			finally {
     
				// Reset common introspection caches in Spring's core, since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}
	}

SpringIOC源码——注册beanPostProcesser

进行一些排序处理以及分类处理

public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
     

		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
	    ……
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
        ……
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
		……
		sortPostProcessors(orderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);
         ……
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
		……
		sortPostProcessors(internalPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, internalPostProcessors);
	    ……
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}

SpringIOC源码——创建bean

finishBeanFactoryInitialization

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
     
		/*
		  value注解解析
		 */
		……
		if (!beanFactory.hasEmbeddedValueResolver()) {
     
			beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
		}
       ……
       /*
         创建开始
        */
		beanFactory.preInstantiateSingletons();
	}

DefaultListableBeanFactory

public void preInstantiateSingletons() throws BeansException {
     
		/*
		  拿到所有名字
		 */
		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

		for (String beanName : beanNames) {
     
		/*
		    将bean信息封装成RootBeanDefinition
		    RootBeanDefinition是一个操作bean核心数据的对象
		  */
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
     
				if (isFactoryBean(beanName)) {
     //isFactoryBean,做一些特殊操作
					……
				}
				else {
     
					getBean(beanName);//继续深入
				}
			}
		}
        /*
          @实现了SmartInitializingSingleton的创建最后的处理
         */
		for (String beanName : beanNames) {
     
			Object singletonInstance = getSingleton(beanName);
			if (singletonInstance instanceof SmartInitializingSingleton) {
     
				final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
				if (System.getSecurityManager() != null) {
     
					AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
     
						smartSingleton.afterSingletonsInstantiated();
						return null;
					}, getAccessControlContext());
				}
				else {
     
					smartSingleton.afterSingletonsInstantiated();
				}
			}
		}
	}	

AbstractBeanFactory

public Object getBean(String name) throws BeansException {
     
		return doGetBean(name, null, null, false);
}
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
			@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
     
		
		/*
		  先去看看缓存看看有没有,三级缓存第二次getBean这里将不返回null
		 */
		final String beanName = transformedBeanName(name);
		Object bean;
		Object sharedInstance = getSingleton(beanName);
		if (sharedInstance != null && args == null) {
     
			……
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}

		else {
     //三级都没有则会直接调用createBean继续
		   ……
		   /*
		     如果父类工厂中存在则用父类工厂创建这些信息
		    */
			BeanFactory parentBeanFactory = getParentBeanFactory();
			if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
     
				
			}
            ……

			try {
      
			    /*
			         封装成RootBeanDefinition
			    */
				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				checkMergedBeanDefinition(mbd, beanName, args);
				 /*
				 检查是否依赖,依赖先创建,会有循环依赖问题,然后递归执行
				 */
				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);
						}
					}
				}

				/*
				  单列bean处理
				 */
				if (mbd.isSingleton()) {
     
					sharedInstance = getSingleton(beanName, () -> {
     
						try {
     
							return createBean(beanName, mbd, args);
						}
						catch (BeansException ex) {
     
							destroySingleton(beanName);
							throw ex;
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}
	            /*
				  多列bean处理
				 */
				else if (mbd.isPrototype()) {
     
					Object prototypeInstance = null;
					try {
     
						beforePrototypeCreation(beanName);
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
     
						afterPrototypeCreation(beanName);
					}
					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
				}
                /*
				  作用域bean处理
				 */
				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, () -> {
     
							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;
			}
		}
	  ……
		return (T) bean;
}

AbstractAutowireCapableBeanFactory——createBean

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

	    ……
	    /*
	       解析class注入RootBeanDefinition中
	     */
		RootBeanDefinition mbdToUse = mbd;
		Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
		if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
     
			mbdToUse = new RootBeanDefinition(mbd);
			mbdToUse.setBeanClass(resolvedClass);
		}
		try {
     
			/*
			   代理模式的返回
			 */
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
			if (bean != null) {
     
				return bean;
			}
		}
		catch (Throwable ex) {
     
			throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
					"BeanPostProcessor before instantiation of bean failed", ex);
		}

		try {
     
		    /*
		      开始创建
		     */
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			if (logger.isTraceEnabled()) {
     
				logger.trace("Finished creating instance of bean '" + beanName + "'");
			}
			return beanInstance;
		}
		catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
     
			throw ex;
		}
		catch (Throwable ex) {
     
			throw new BeanCreationException(
					mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
		}
}

AbstractAutowireCapableBeanFactory——doCreateBean

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
			throws BeanCreationException {
     
		BeanWrapper instanceWrapper = null;
		/*
		  @创建实例,优先调用无参构造器
         */.
		if (mbd.isSingleton()) {
     
			instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
		}
		if (instanceWrapper == null) {
     
			instanceWrapper = createBeanInstance(beanName, mbd, args);
		}
		final Object bean = instanceWrapper.getWrappedInstance();
		Class<?> beanType = instanceWrapper.getWrappedClass();
		if (beanType != NullBean.class) {
     
			mbd.resolvedTargetType = beanType;
		}

		/*
		  @MergedBeanDefinitionPostProcessors
         */.
		synchronized (mbd.postProcessingLock) {
     
			if (!mbd.postProcessed) {
     
				try {
     
					applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				}
				catch (Throwable ex) {
     
					throw new BeanCreationException(mbd.getResourceDescription(), beanName,
							"Post-processing of merged bean definition failed", ex);
				}
				mbd.postProcessed = true;
			}
		}
       /*
        * 这里开始提前暴露引用,加入三级缓存,但是只是加入一个工厂返回bean
        */
		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));
		}

		Object exposedObject = bean;
		try {
     
		    /*
		      赋值的时候可能依赖另外一个bean,继续递归调用getBean方法
		     */
			populateBean(beanName, mbd, instanceWrapper);
			/*
			 调用ioc意义的初始化方法
			 */
			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(……)
					}
				}
			}
		}

		/*
		   注册需要销毁通知的bean到
         */
		try {
     
			registerDisposableBeanIfNecessary(beanName, bean, mbd);
		}
		catch (BeanDefinitionValidationException ex) {
     
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
		}

		return exposedObject;
	}

SpringIOC源码——beanFactory简单api

/*
  registerSingleton是可以对外暴露的api
  最后所有实例对象放入到singletonObjects内都是真实已经存在的对象
 */
	public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
     
		Assert.notNull(beanName, "Bean name must not be null");
		Assert.notNull(singletonObject, "Singleton object must not be null");
		synchronized (this.singletonObjects) {
     
			Object oldObject = this.singletonObjects.get(beanName);
			if (oldObject != null) {
     
				throw new IllegalStateException("Could not register object [" + singletonObject +
						"] under bean name '" + beanName + "': there is already object [" + oldObject + "] bound");
			}
			addSingleton(beanName, singletonObject);
		}
	}
	protected void addSingleton(String beanName, Object singletonObject) {
     
		synchronized (this.singletonObjects) {
     
			this.singletonObjects.put(beanName, singletonObject);
			this.singletonFactories.remove(beanName);
			this.earlySingletonObjects.remove(beanName);
			this.registeredSingletons.add(beanName);
		}
	}
	/*
	   用于解决循环引用问题,有一些对象创建在singletonFactories中
	 */
	protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
     
		Assert.notNull(singletonFactory, "Singleton factory must not be null");
		synchronized (this.singletonObjects) {
     
			if (!this.singletonObjects.containsKey(beanName)) {
     
				this.singletonFactories.put(beanName, singletonFactory);
				this.earlySingletonObjects.remove(beanName);
				this.registeredSingletons.add(beanName);
			}
		}
	}

SpringIOC源码——整体流程——总结

(1)初始化期间,我们实现一个父工厂、重建一个工厂、工厂后置处理来实现工厂的行为的改变;
(2)初始化期间,会先实例化所有具有beanpostprocesser的类;
(3)获取bean:AbstractBeanFactory会加载所有定义信息,然后去获取bean;获取不到就会去调用下面的创建bean
(4)创建bean,AbstractAutowireCapableBeanFactory是主要助处理创建bean的类,内置很多postprocesser的调用以及解决循环引用的问题关键还有单利和多例的创建方式

那么清晰了整个SpringIOC创建的整体流程,我们后续在详细剖析依赖注入和循环引用问题是如何解决就非常方便了;

你可能感兴趣的:(Java框架源码,spring,java)