<output id="qn6qe"></output>

    1. <output id="qn6qe"><tt id="qn6qe"></tt></output>
    2. <strike id="qn6qe"></strike>

      亚洲 日本 欧洲 欧美 视频,日韩中文字幕有码av,一本一道av中文字幕无码,国产线播放免费人成视频播放,人妻少妇偷人无码视频,日夜啪啪一区二区三区,国产尤物精品自在拍视频首页,久热这里只有精品12

      10.Java Spring框架源碼分析-IOC-實例化所有非懶加載的單實例bean

      1. 要研究的代碼

      • finishBeanFactoryInitialization
      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.
      	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.
      	//實例化所有剩下的非懶加載的單實例bean
      	beanFactory.preInstantiateSingletons();
      }
      

      這個步驟中尤其重要,他的preInstantiateSingletons會實例化所有非懶加載的單實例bean

      2. 實例化所有非懶加載的單實例bean

      2.1. 獲取所有BeanName,一個個創建

      • DefaultListableBeanFactory preInstantiateSingletons
      public void preInstantiateSingletons() throws BeansException {
      	if (logger.isDebugEnabled()) {
      		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) {
      		//封裝成RootBeanDefinition
      		RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
      		//不是抽象的、是單例的、不是懶加載的
      		if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
      			//是FactoryBean類型的(Spring提供的工廠模式,有一個getObject創建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);
      				}
      			}
      			//不是FactoryBean
      			else {
      				//調用AbstractBeanFactory的getBean
      				getBean(beanName);
      			}
      		}
      	}
      
      	// Trigger post-initialization callback for all applicable beans...
      	//遍歷所有bean
      	for (String beanName : beanNames) {
      		Object singletonInstance = getSingleton(beanName);
      		//如果這個bean是SmartInitializingSingleton類型的
      		if (singletonInstance instanceof SmartInitializingSingleton) {
      			final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
      			if (System.getSecurityManager() != null) {
      				AccessController.doPrivileged(new PrivilegedAction<Object>() {
      					@Override
      					public Object run() {
      						smartSingleton.afterSingletonsInstantiated();
      						return null;
      					}
      				}, getAccessControlContext());
      			}
      			else {
      				//調用其afterSingletonsInstantiated方法
      				smartSingleton.afterSingletonsInstantiated();
      			}
      		}
      	}
      }
      

      2.2. 創建單個bean

      • AbstractBeanFactory getBean
      @Override
      public Object getBean(String name) throws BeansException {
      //傳入beanName
      return doGetBean(name, null, null, false);
      }
      

      2.3. 看看之前創建bean有木有,沒有再去創建【不是緩存,而是之前步驟創建的Bean】

      • doGetBean
      protected <T> T doGetBean(
      		final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
      		throws BeansException {
      
      	final String beanName = transformedBeanName(name);
      	Object bean;
      
      	// Eagerly check singleton cache for manually registered singletons.
      	//從之前預加載的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中有
      		bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
      	}
      	//之前預加載的bean中沒有
      	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獲取bean
      		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);
      			}
      		}
      
      		if (!typeCheckOnly) {
      			//標記當前bean已創建
      			markBeanAsCreated(beanName);
      		}
      
      		try {
      			final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
      			checkMergedBeanDefinition(mbd, beanName, args);
      
      			// Guarantee initialization of beans that the current bean depends on.
      			//獲取當前bean依賴的其他bean 指的是@DependsOn("。。。。")
      			String[] dependsOn = mbd.getDependsOn();
      			if (dependsOn != null) {
      				//遍歷其他bean
      				for (String dep : dependsOn) {
      					//如果其他bean也依賴當前bean
      					if (isDependent(beanName, dep)) {
      					//拋出循環依賴異常
      						throw new BeanCreationException(mbd.getResourceDescription(), beanName,
      								"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
      					}
      					//注冊依賴bean
      					registerDependentBean(dep, beanName);
      					//獲取依賴bean,獲取不到則拋出不存在的異常
      					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()) {
      				//回調第二個參數的getObject方法,最后調用createBean方法創建bean
      				sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
      					@Override
      					public Object getObject() throws BeansException {
      						try {
      						    //創建bean實例
      							return createBean(beanName, mbd, args);
      						}
      						//創建失敗銷毀bean
      						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);
      			}
      			//prototype的
      			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);
      			}
      			//其他的:session等
      			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;
      }
      

      2.4. 從緩存中獲取,沒有再創建

      • DefaultSingletonBeanRegistry getSingleton
      public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
      	Assert.notNull(beanName, "'beanName' must not be null");
      	//加鎖
      	synchronized (this.singletonObjects) {
      		//從緩存map中獲取
      		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 {
      				//通過beanFactory創建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;
      				}
      				//bean創建之后調用
      				afterSingletonCreation(beanName);
      			}
      			if (newSingleton) {
      				//把新創建的bean放入map中(ioc容器)
      				addSingleton(beanName, singletonObject);
      			}
      		}
      		return (singletonObject != NULL_OBJECT ? singletonObject : null);
      	}
      }
      

      2.5. 先看看能不能返回代理對象,不能再創建

      • AbstractAutowireCapableBeanFactory createBean
      protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
      	if (logger.isDebugEnabled()) {
      		logger.debug("Creating instance of bean '" + beanName + "'");
      	}
      	//bean的定義
      	RootBeanDefinition mbdToUse = mbd;
      
      	// Make sure bean class is actually resolved at this point, and
      	// clone the bean definition in case of a dynamically resolved Class
      	// which cannot be stored in the shared merged bean definition.
      	//拿到bean的類型
      	Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
      	if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
      		mbdToUse = new RootBeanDefinition(mbd);
      		mbdToUse.setBeanClass(resolvedClass);
      	}
      
      	// Prepare method overrides.
      	try {
      		mbdToUse.prepareMethodOverrides();
      	}
      	catch (BeanDefinitionValidationException ex) {
      		throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
      				beanName, "Validation of method overrides failed", ex);
      	}
      
      	try {
      		// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
      		//這里BeanPostProcessor可以返回代理對象
      		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);
      	}
      
      	//真正創建bean
      	Object beanInstance = doCreateBean(beanName, mbdToUse, args);
      	if (logger.isDebugEnabled()) {
      		logger.debug("Finished creating instance of bean '" + beanName + "'");
      	}
      	return beanInstance;
      }
      

      2.5.1. 從代理對象中獲取

      2.5.1.1. 第一次創建業務bean進到這里的時候并不會返回代理對象

      舉個例子,如果我們有一個業務Bean叫Calc,他的代理Bean叫CalcProxy

      • 第一次從容器中獲取Calc Bean的場景

        • 從容器中獲取Calc Bean
        • 進入到這里的時候既沒有Bean Calc也沒有Bean CalcProxy,所以不會返回代理bean
        • 真正創建業務Bean Calc
        • 然后調用執行所有PostProcessor的postProcessAfterInitialization方法創建代理對象
      • 第二次從容器中獲取Calc Bean的場景

        • 從容器中獲取Calc Bean
        • 由于容器中沒有,需要先創建業務Bean Calc
        • 進入到這里的時候已經有了代理Bean CalcProxy,返回
      • resolveBeforeInstantiation

      protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
      	Object bean = null;
      	if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
      		// Make sure bean class is actually resolved at this point.
      		//調用AbstractBeanFactory的hasInstantiationAwareBeanPostProcessors方法查看是否包含InstantiationAwareBeanPostProcessors類型的PostProcessor
      		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      			Class<?> targetType = determineTargetType(beanName, mbd);
      			if (targetType != null) {
      				//調用InstantiationAwareBeanPostProcessor類型的postProcessBeforeInstantiation方法獲取代理對象
      				bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
      				if (bean != null) {
      					//代理對象不為空那么調用postProcessAfterInitialization方法操作bean
      					bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
      				}
      			}
      		}
      		mbd.beforeInstantiationResolved = (bean != null);
      	}
      	return bean;
      }
      

      通過調用InstantiationAwareBeanPostProcessor類型的postProcessBeforeInstantiation方法獲取代理對象,有的話再調用postProcessAfterInitialization方法操作bean,并返回

      2.5.1.2. 在實例化之前調用
      • applyBeanPostProcessorsBeforeInstantiation
      protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
      	//遍歷所有BeanPostProcessor
      	for (BeanPostProcessor bp : getBeanPostProcessors()) {
      		//如果是InstantiationAwareBeanPostProcessor類型的
      		if (bp instanceof InstantiationAwareBeanPostProcessor) {
      			InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
      			//那么調用postProcessBeforeInstantiation方法獲取代理對象
      			Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
      			if (result != null) {
      				return result;
      			}
      		}
      	}
      	return null;
      }
      
      2.5.1.3. 如果有代理對象那么調用
      • applyBeanPostProcessorsAfterInitialization
      public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
      		throws BeansException {
      
      	Object result = existingBean;
      	//遍歷所有BeanPostProcessor
      	for (BeanPostProcessor processor : getBeanPostProcessors()) {
      		//調用postProcessAfterInitialization方法操作bean	
      		result = processor.postProcessAfterInitialization(result, beanName);
      		if (result == null) {
      			return result;
      		}
      	}
      	return result;
      }
      

      2.6. 真正創建bean實例

      • doCreateBean
      protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
      		throws BeanCreationException {
      
      	// Instantiate the bean.
      	BeanWrapper instanceWrapper = null;
      	if (mbd.isSingleton()) {
      		instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
      	}
      	if (instanceWrapper == null) {
      		//創建bean對象
      		instanceWrapper = createBeanInstance(beanName, mbd, args);
      	}
      	final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
      	Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
      	mbd.resolvedTargetType = beanType;
      
      	// Allow post-processors to modify the merged bean definition.
      	synchronized (mbd.postProcessingLock) {
      		if (!mbd.postProcessed) {
      			try {
      				//調用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition方法
      				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.isDebugEnabled()) {
      			logger.debug("Eagerly caching bean '" + beanName +
      					"' to allow for resolving potential circular references");
      		}
      		addSingletonFactory(beanName, new ObjectFactory<Object>() {
      			@Override
      			public Object getObject() throws BeansException {
      				return getEarlyBeanReference(beanName, mbd, bean);
      			}
      		});
      	}
      
      	// Initialize the bean instance.
      	Object exposedObject = bean;
      	try {
      		//為bean的屬性賦值
      		populateBean(beanName, mbd, instanceWrapper);
      		if (exposedObject != null) {
      			//初始化bean
      			exposedObject = initializeBean(beanName, exposedObject, mbd);
      		}
      	}
      	catch (Throwable ex) {
      		if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
      			throw (BeanCreationException) ex;
      		}
      		else {
      			throw new BeanCreationException(
      					mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
      		}
      	}
      
      	if (earlySingletonExposure) {
      		Object earlySingletonReference = getSingleton(beanName, false);
      		if (earlySingletonReference != null) {
      			if (exposedObject == bean) {
      				exposedObject = earlySingletonReference;
      			}
      			else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
      				String[] dependentBeans = getDependentBeans(beanName);
      				Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
      				for (String dependentBean : dependentBeans) {
      					if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
      						actualDependentBeans.add(dependentBean);
      					}
      				}
      				if (!actualDependentBeans.isEmpty()) {
      					throw new BeanCurrentlyInCreationException(beanName,
      							"Bean with name '" + beanName + "' has been injected into other beans [" +
      							StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
      							"] in its raw version as part of a circular reference, but has eventually been " +
      							"wrapped. This means that said other beans do not use the final version of the " +
      							"bean. This is often the result of over-eager type matching - consider using " +
      							"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
      				}
      			}
      		}
      	}
      
      	// Register bean as disposable.
      	try {
      		//注冊bean的銷毀方法,registerDisposableBeanIfNecessary
      		不是調用(beanName, bean, mbd);
      	}
      	catch (BeanDefinitionValidationException ex) {
      		throw new BeanCreationException(
      				mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
      	}
      
      	return exposedObject;
      }
      

      創建實例的時候分成以下幾個步驟

      1. 創建bean實例
      2. 為bean的屬性賦值
      3. 初始化bean

      2.6.1. 創建bean實例

      • createBeanInstance
      protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
      	// Make sure bean class is actually resolved at this point.
      	//獲取bean的類型
      	Class<?> beanClass = resolveBeanClass(mbd, beanName);
      
      	if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
      		throw new BeanCreationException(mbd.getResourceDescription(), beanName,
      				"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
      	}
      
      	//使用工廠方法創建bean
      	if (mbd.getFactoryMethodName() != null) {
      		return instantiateUsingFactoryMethod(beanName, mbd, args);
      	}
      
      	// Shortcut when re-creating the same bean...
      	//調用bean的有參構造方法
      	boolean resolved = false;
      	boolean autowireNecessary = false;
      	if (args == null) {
      		synchronized (mbd.constructorArgumentLock) {
      			if (mbd.resolvedConstructorOrFactoryMethod != null) {
      				resolved = true;
      				autowireNecessary = mbd.constructorArgumentsResolved;
      			}
      		}
      	}
      	if (resolved) {
      		if (autowireNecessary) {
      			return autowireConstructor(beanName, mbd, null, null);
      		}
      		else {
      			return instantiateBean(beanName, mbd);
      		}
      	}
      
      	// Candidate constructors for autowiring?
      	Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
      	if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
      			mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
      		return autowireConstructor(beanName, mbd, ctors, args);
      	}
      
      	// No special handling: simply use no-arg constructor.
      	//調用bean的無參構造方法
      	return instantiateBean(beanName, mbd);
      }
      

      2.6.2. 為bean的屬性賦值

      • populateBean
      protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
      	//拿到所有的屬性值
      	PropertyValues pvs = mbd.getPropertyValues();
      
      	if (bw == null) {
      		if (!pvs.isEmpty()) {
      			throw new BeanCreationException(
      					mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
      		}
      		else {
      			// Skip property population phase for null instance.
      			return;
      		}
      	}
      
      	// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
      	// state of the bean before properties are set. This can be used, for example,
      	// to support styles of field injection.
      	boolean continueWithPropertyPopulation = true;
      
      	//有InstantiationAwareBeanPostProcessor類型的PostProcessor
      	if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
      		//遍歷所有PostProcessor
      		for (BeanPostProcessor bp : getBeanPostProcessors()) {
      			//調用InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation方法
      			if (bp instanceof InstantiationAwareBeanPostProcessor) {
      				InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
      				if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
      					continueWithPropertyPopulation = false;
      					break;
      				}
      			}
      		}
      	}
      
      	if (!continueWithPropertyPopulation) {
      		return;
      	}
      
      	if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
      			mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
      		MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
      
      		// Add property values based on autowire by name if applicable.
      		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
      			autowireByName(beanName, mbd, bw, newPvs);
      		}
      
      		// Add property values based on autowire by type if applicable.
      		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
      			autowireByType(beanName, mbd, bw, newPvs);
      		}
      
      		pvs = newPvs;
      	}
      
      	boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
      	boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
      
      	if (hasInstAwareBpps || needsDepCheck) {
      		PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
      		if (hasInstAwareBpps) {
      			//遍歷所有PostProcessor
      			for (BeanPostProcessor bp : getBeanPostProcessors()) {
      				//調用InstantiationAwareBeanPostProcessor的postProcessPropertyValues方法
      				if (bp instanceof InstantiationAwareBeanPostProcessor) {
      					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
      					pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
      					if (pvs == null) {
      						return;
      					}
      				}
      			}
      		}
      		if (needsDepCheck) {
      			checkDependencies(beanName, mbd, filteredPds, pvs);
      		}
      	}
      	//調用setter方法為屬性賦值
      	applyPropertyValues(beanName, mbd, bw, pvs);
      }
      

      屬性賦值有三個操作

      • 調用InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation方法
      • 調用InstantiationAwareBeanPostProcessor的postProcessPropertyValues方法
      • 調用setter方法為屬性賦值

      2.6.3. 初始化bean

      • initializeBean
      protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
      	if (System.getSecurityManager() != null) {
      		AccessController.doPrivileged(new PrivilegedAction<Object>() {
      			@Override
      			public Object run() {
      				invokeAwareMethods(beanName, bean);
      				return null;
      			}
      		}, getAccessControlContext());
      	}
      	else {
      		//執行XXXAware接口的方法
      		invokeAwareMethods(beanName, bean);
      	}
      
      	Object wrappedBean = bean;
      	if (mbd == null || !mbd.isSynthetic()) {
      		//執行所有PostProcessor的postProcessBeforeInitialization方法
      		wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
      	}
      
      	try {
      		//調用自定義的初始化方法
      		invokeInitMethods(beanName, wrappedBean, mbd);
      	}
      	catch (Throwable ex) {
      		throw new BeanCreationException(
      				(mbd != null ? mbd.getResourceDescription() : null),
      				beanName, "Invocation of init method failed", ex);
      	}
      	if (mbd == null || !mbd.isSynthetic()) {
      		//調用所有BeanPostProcessor的postProcessAfterInitialization方法
      		wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
      	}
      	return wrappedBean;
      }
      
      2.6.3.1. 執行所有BeanPostProcessor的postProcessBeforeInitialization方法
      • applyBeanPostProcessorsBeforeInitialization
      public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
      		throws BeansException {
      
      	Object result = existingBean;
      	//遍歷所有PostProcessor,調用postProcessBeforeInitialization方法
      	for (BeanPostProcessor processor : getBeanPostProcessors()) {
      		result = processor.postProcessBeforeInitialization(result, beanName);
      		if (result == null) {
      			return result;
      		}
      	}
      	return result;
      }
      
      2.6.3.2. 調用自定義的初始化方法【InitializingBean】
      • invokeInitMethods
      protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
      		throws Throwable {
      
      	//是InitializingBean對象
      	boolean isInitializingBean = (bean instanceof InitializingBean);
      	if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
      		if (logger.isDebugEnabled()) {
      			logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
      		}
      		if (System.getSecurityManager() != null) {
      			try {
      				AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
      					@Override
      					public Object run() throws Exception {
      						((InitializingBean) bean).afterPropertiesSet();
      						return null;
      					}
      				}, getAccessControlContext());
      			}
      			catch (PrivilegedActionException pae) {
      				throw pae.getException();
      			}
      		}
      		else {
      			//調用bean的afterPropertiesSet方法
      			((InitializingBean) bean).afterPropertiesSet();
      		}
      	}
      
      	if (mbd != null) {
      		String initMethodName = mbd.getInitMethodName();
      		if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
      				!mbd.isExternallyManagedInitMethod(initMethodName)) {
      			//執行自定義的初始化方法
      			invokeCustomInitMethod(beanName, bean, mbd);
      		}
      	}
      }
      
      2.6.3.3. 調用所有BeanPostProcessor的postProcessAfterInitialization方法

      這里會創建代理bean

      • applyBeanPostProcessorsAfterInitialization
      public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
      		throws BeansException {
      
      	Object result = existingBean;
      	//遍歷所有BeanPostProcessor
      	for (BeanPostProcessor processor : getBeanPostProcessors()) {
      		//調用postProcessAfterInitialization方法
      		result = processor.postProcessAfterInitialization(result, beanName);
      		if (result == null) {
      			return result;
      		}
      	}
      	return result;
      }
      

      2.6.4. 注冊bean的銷毀方法

      • registerDisposableBeanIfNecessary
      protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
      	AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
      	if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
      		if (mbd.isSingleton()) {
      			// Register a DisposableBean implementation that performs all destruction
      			// work for the given bean: DestructionAwareBeanPostProcessors,
      			// DisposableBean interface, custom destroy method.
      			registerDisposableBean(beanName,
      					new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
      		}
      		else {
      			// A bean with a custom scope...
      			Scope scope = this.scopes.get(mbd.getScope());
      			if (scope == null) {
      				throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
      			}
      			scope.registerDestructionCallback(beanName,
      					new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
      		}
      	}
      }
      
      posted @ 2025-07-04 21:23  ThinkerQAQ  閱讀(149)  評論(0)    收藏  舉報
      主站蜘蛛池模板: 国产主播精品福利午夜二区| 亚洲最大的成人网站| 40岁大乳的熟妇在线观看| 亚洲精品熟女一区二区| 男女性高爱潮免费网站| 免费无码影视在线观看mov| 国产成人午夜精品福利| 国产精品爽爽v在线观看无码| av一本久道久久综合久久鬼色| 亚洲欧美激情在线一区| 国产精品亚洲二区亚瑟| av偷拍亚洲一区二区三区| 亚洲国产精品一区二区视频| 99精品国产在热久久婷婷| 亚洲狼人久久伊人久久伊| 亚洲综合色丁香婷婷六月图片| 国产女人喷潮视频在线观看| 久久久久久久一线毛片| 色狠狠色噜噜AV一区| 成人精品国产一区二区网| 成人福利一区二区视频在线| 亚洲一区二区三区小蜜桃| 94人妻少妇偷人精品| 亚洲人成电影在线天堂色| 亚洲av色综合久久综合| 中文字幕乱妇无码AV在线| 不卡一区二区三区四区视频| 人妻系列无码专区免费| 久久精品无码免费不卡| 国内精品综合九九久久精品| 欧美性猛交xxxx黑人| 久久亚洲日韩精品一区二区三区| 亚洲欧美精品在线| 综合欧美视频一区二区三区| 国产精品亚洲综合第一页| 无码国产一区二区三区四区| 国产精品久久欧美久久一区| 免费无码一区无码东京热| 丰满少妇被猛烈进入av久久| 国产三级精品片| 欧美人与禽2o2o性论交|