spring-iocBean實例化的流程


public void refresh() throws BeansException, IllegalStateException {
		/**
		 * 加鎖,說明併發執行,很多地方都有調用
		 * registerShutdownHook 也調用了
		 * close()方法也調有了,
		 * 容器在啓動時,不能調Close的方法
		 */
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			/**
			 * 預初始化
			 */
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			/**
			 *
			 * 創建BeanFactory工廠,告訴子類去刷新內部BeanFactory,
			 * 加載Bean信息,並封裝爲BeanDefinition,並註冊到BeanDefinitionRegistry
			 * key-value key :bean的id value就是BeanDefinition
			 */
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			/**
			 * 準備BeanFactory,進行一些設置
			 * Context的類加載器
			 */
			prepareBeanFactory(beanFactory);

			try {
				/**
				 * BeanFactory準備完成後,後置處理器增強,空方法
				 */
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);


				// Invoke factory processors registered as beans in the context.
				/**
				 * 實例化實現了BeanFactoryPostProcessor接口的類中構造方法
				 * 並調用用postProcessBeanFactory 方法
				 *
				 */
				invokeBeanFactoryPostProcessors(beanFactory);


				// Register bean processors that intercept bean creation.
				/**
				 *將實現了BeanPostProcessor的構造方法
				 */
				registerBeanPostProcessors(beanFactory);

				/**
				 * 初始化國際華資源MessageSource組牛
				 */
				// Initialize message source for this context.
				initMessageSource();

				/**
				 * 初始化事件派發器
				 */
				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				/**
				 * 空方法
				 * 如果子類重寫了這個方法就,調用子類重寫的方法tomcat jetty之類的
				 */
				// Initialize other special beans in specific context subclasses.
				onRefresh();

				/**
				 * 註冊應用監聽器就是實現了ApplicationContextListener接口Bean
				 */
				// Check for listener beans and register them.
				registerListeners();
					/**
					 * 執行構造方法1
					 * setter方法2
					 * 實現了BeanNameAware接口的setBeanName方法3
					 * 實現了BeanFactoryAware接口的 setBeanFactory(BeanFactory beanFactory)方法4
					 * 實現了ApplicationContextAware接口的setsetApplicationContext 方法5
					 * 實現了BeanPostProcessor接口的postProcessBeforeInitialization方法6 ,AOP原理
					 * 標有PostConstruct註解的方法 7
					 * 實現了InitializingBean接口的afterPropertiesSet方法8
					 * 調用配置了init-method方法 9
					 * 實現了BeanPostProcessor接口的postProcessAfterInitialization方法 10
					 *
					 */
				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

				/**
				 * 完成刷新Context,主要調用org.springframework.context.LifecycleProcessor接口onRefresh方法,發佈事件ContextRefreshedEvent事件
				 */
				// Last step: publish corresponding event.
				finishRefresh();
			}
```

#### finishBeanFactoryInitialization方法
org.springframework.context.support.AbstractApplicationContext#finishBeanFactoryInitialization
```java
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
....
		/**
		 * 實例化所有非懶加載的Bean也就是單例的Bean
		 */
		// Instantiate all remaining (non-lazy-init) singletons.
		beanFactory.preInstantiateSingletons();
	}

```

#### beanFactory.preInstantiateSingletons
org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons
```java
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.
		/**
		 * 獲取所有Bean的name也就是id
		 */
		List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

		// Trigger initialization of all non-lazy singleton beans...
		for (String beanName : beanNames) {
			//合併父BeanDefinition對象
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				if (isFactoryBean(beanName)) {
					/**
					 * 如果是FactoryBean就在前面加&符號
					 * 	String FACTORY_BEAN_PREFIX = "&";
					 */
					Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
					if (bean instanceof FactoryBean) {
						final 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(beanName);
				}
			}
		}
```
### getBean
```java

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

		/**
		 * 獲取BeanName,,id
		 */
		final String beanName = transformedBeanName(name);
		Object bean;

		/**
		 * 獲取單例對象
		 */
		// Eagerly check singleton cache for manually registered singletons.
		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 {
				/**
				 * 合併父BeanDefinition
				 */
				final 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);
						}
					}
				}

				/**
				 * 創建單例的Bean
				 */
				// Create bean instance.
				if (mbd.isSingleton()) {
					sharedInstance = getSingleton(beanName, () -> {
						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, () -> {
							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;
	}
```


org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])

````java

try {
			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
			if (logger.isTraceEnabled()) {
				logger.trace("Finished creating instance of bean '" + beanName + "'");
			}
			return beanInstance;
		}
```
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章