AnnotationConfigApplicationContext容器初始化目錄
(Spring源碼分析)AnnotationConfigApplicationContext容器初始化 this() && register()
(Spring源碼分析)AnnotationConfigApplicationContext容器初始化 refresh()#invokeBeanFactoryPostProcessors
(Spring源碼分析)AnnotationConfigApplicationContext容器初始化 refresh()#registerBeanPostProcessors
(Spring源碼分析)AnnotationConfigApplicationContext容器初始化 refresh()#finishBeanFactoryInitialization
目錄
- 3.3、finishBeanFactoryInitialization(beanFactory)
- beanFactory.preInstantiateSingletons()
- getBean(beanName)
- doGetBean(name, null, null, false)
- getSingleton(beanName)
- createBean(beanName, mbd, args)
- resolveBeforeInstantiation(beanName, mbdToUse)
- applyBeanPostProcessorsBeforeInstantiation(targetType, beanName)
- applyBeanPostProcessorsAfterInitialization(bean, beanName)
- doCreateBean(beanName, mbdToUse, args)
- applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)
- bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName)
- populateBean(beanName, mbd, instanceWrapper)
- getSingleton(beanName, singletonFactory)
3.3、finishBeanFactoryInitialization(beanFactory)
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(strVal -> 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();
}
beanFactory.preInstantiateSingletons()
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isDebugEnabled()) {
logger.debug("Pre-instantiating singletons in " + this);
}
// 所有bean的beanName
// 可能需要實例化的class(lazy、scope):懶加載的不實例化,非單例的不實例化
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// 觸發所有非延遲加載單例beans的初始化,主要步驟爲調用getBean()方法來對bean進行初始化
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { // 當BeanDefinition是抽象的,並且不是單例的,並且是懶加載的就不實例化bean
if (isFactoryBean(beanName)) { // 當該bean繼承了FactoryBean時
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); // 初始化該bean
}
}
}
// Trigger post-initialization callback for all applicable beans...
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();
}
}
}
}
getBean(beanName)
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
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 {
// 這裏不直接name主要是因爲alias和FactoryBean的原因
// 1、別名需要轉換成真正的beanName
// 2、如果傳入的name是實現了FactoryBean接口的話,那麼傳入的name是以&開頭的,需要將首字母&移除
final String beanName = transformedBeanName(name); // 獲取beanName
Object bean;
// 這個方法在初始化的時候會調用,在getBean的時候也會調用,原因:
//
// 嘗試從三級緩存中獲取bean實例
//
// Spring循環依賴的原理:
// 在創建單例bean的時候會存在依賴注入的情況,爲了避免循環依賴,Spring在創建bean的原則是不等bean創建完成就會將創建bean的ObjectFactory提早曝光,添加到singletonFactories中
// 將ObjectFactory加入到緩存中,一旦下一個bean創建的時候需要依賴注入上個bean則直接從緩存中獲取ObjectFactory
Object sharedInstance = getSingleton(beanName); // 根據beanName嘗試從三級緩存中獲取bean實例
// 當三級緩存中存在此bean,表示當前該bean已創建完成 || 正在創建
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
// 該bean在singletonFactories,但是還未初始化,因爲此bean存在循環依賴
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly caFFched 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 + "'");
}
}
// 返回對應的實例,有時候存在諸如BeanFactory的情況並不是直接返回實例本身而是返回指定方法返回的實例
// 如果sharedInstance是普通的單例bean,下面的方法會直接返回,但如果sharedInstance是FactoryBean類型的,
// 則需要調用getObject工廠方法獲取bean實例,如果用戶想獲取FactoryBean本身,這裏也不會做特別的處理
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
// 當bean還未創建
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
// 如果該bean的scope是原型(phototype)不應該在初始化的時候創建
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
// 檢查當前容器是否有父容器
BeanFactory parentBeanFactory = getParentBeanFactory();
// 如果父容器中存在此bean的實例,直接從父容器中獲取bean的實例並返回
// 父子容器:Spring和SpringMVC都是一個容器,Spring容器是父容器,SpringMVC是子容器
// controller的bean放在SpringMVC的子容器中,service、mapper放在Spring父容器中
// 子容器可以訪問父容器中的bean實例,父容器不可以訪問子容器中的實例
// controller中可以注入service的依賴,但是service不能注入controller的依賴
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 {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
if (!typeCheckOnly) {
// 添加到alreadyCreated set集合當中,表示他已經創建過了
markBeanAsCreated(beanName);
}
try {
// 從父容器中的BeanDefinitionMap和子容器中的BeanDefinitionMap合併的BeanDefinitionMap中獲取BeanDefinition對象
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
// 獲取當前bean依賴注入的的屬性,bean的初始化之前裏面依賴的屬性必須先初始化
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.
// 正式開始創建bean實例
if (mbd.isSingleton()) { // 當該bean的scope爲singleton或者爲空時
sharedInstance = getSingleton(beanName, () -> { // 從三級緩存中獲取bean實例
try {
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 類型的 bean 實例
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);
}
// 創建其他類型的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;
}
}
// 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.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(beanName)
@Override
@Nullable
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
getSingleton(beanName, true)
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) { // allowEarlyReference表示是否允許從singletonFactories中通過getObject拿到對象
// 嘗試從三級緩存中獲取bean實例
Object singletonObject = this.singletonObjects.get(beanName); // 從一級緩存中獲取bean
// 如果一級緩存中不存在該bean實例 && 該bean正在創建中
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { // isSingletonCurrentlyInCreation(beanName)判斷這個bean是否在創建過程中,對象是否有循環依賴
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName); // 嘗試從二級緩存中獲取bean實例
// 如果二級緩存中不存在giantbean實例 && 允許從singletonFactories從獲取bean實例
if (singletonObject == null && allowEarlyReference) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); // 從三級緩存中獲取bean實例
// 如果bean存在,將該bean實例從三級緩存升級到二級緩存中,並且從三級緩存中刪除
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
createBean(beanName, mbd, args)
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
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.
// 主要是來執行實現了InstantiationAwareBeanPostProcessor接口的BeanPostProcesser,但是返回的bean始終爲null
// AOP核心方法,用來處理使用@Aspect註解標識的bean,以便後面生成動態代理
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
// 生成的bean實例存在就返回
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
// 實例化bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
resolveBeforeInstantiation(beanName, mbdToUse)
@Nullable
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.
// hasInstantiationAwareBeanPostProcessors()是來判斷容器中是否有InstantiationAwareBeanPostProcessor的實現bean
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, mbd); // 獲取bean的目標類型
if (targetType != null) {
// 執行實現了InstantiationAwareBeanPostProcessor接口的BeanPostProcessor中的前置處理方法postProcessBeforeInstantiation方法
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
// 執行實現了InstantiationAwareBeanPostProcessor接口的BeanPostProcessor中的後置處理方法postProcessAfterInitialization方法
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
applyBeanPostProcessorsBeforeInstantiation(targetType, beanName)
@Nullable
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
applyBeanPostProcessorsAfterInitialization(bean, beanName)
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
doCreateBean(beanName, mbdToUse, args)
/**
* 初始化bean實例(解決循環依賴問題)
*/
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// 調用bean的構造方法進行初始化,經過這一步,bean屬性並沒有被賦值,只是一個空殼,這是bean初始化的【早期對象】
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
// 創建bean實例轉化成BeanWrapper對象
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final 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 {
// 處理bean中實現了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.
// 判斷bean是否存在循環依賴
// 如果當前bean是單例,且支持循環依賴,且當前bean正在創建,通過往singletonFactories添加一個objectFactory,這樣後期如果有其他bean依賴該bean 可以從singletonFactories獲取到bean
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");
}
// 解決Spring循環依賴問題
// 添加工廠對象到singletonFactories緩存中【提前暴露早期對象】
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
// 初始化bean實例
Object exposedObject = bean;
try {
// 給已經已經初始化的屬性賦值,包括完成bean的依賴注入
populateBean(beanName, mbd, instanceWrapper);
// 初始化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<>(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 {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName)
MergedBeanDefinitionPostProcessor的實現類可以用來處理@Autowired、@Value、@PostConstruct、@PreDestroy、@Scheduled等Spring提供的註解
下面以實現類AutowiredAnnotationBeanPostProcessor用來處理@Autowired、@Value註解舉例
當bdp的實現類是AutowiredAnnotationBeanPostProcessor時,將調用AutowiredAnnotationBeanPostProcessor重寫的postProcessMergedBeanDefinition方法
@Override
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
metadata.checkConfigMembers(beanDefinition);
}
findAutowiringMetadata(beanName, beanType, null)
private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
// Fall back to class name as cache key, for backwards compatibility with custom callers.
String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
// Quick check on the concurrent map first, with minimal locking.
InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
synchronized (this.injectionMetadataCache) {
metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
if (metadata != null) {
metadata.clear(pvs);
}
// 解析等待依賴注入類的所有屬性,構建InjectionMetadata對象,它是通過分析類中所有屬性和所有方法中是否有該註解
metadata = buildAutowiringMetadata(clazz);
this.injectionMetadataCache.put(cacheKey, metadata);
}
}
}
return metadata;
}
buildAutowiringMetadata(clazz)
private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
Class<?> targetClass = clazz;
do {
final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
// 掃描所有屬性
ReflectionUtils.doWithLocalFields(targetClass, field -> {
// 通過分析屬於一個字段的所有註解來查找@Autowired註解
AnnotationAttributes ann = findAutowiredAnnotation(field);
if (ann != null) {
if (Modifier.isStatic(field.getModifiers())) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation is not supported on static fields: " + field);
}
return;
}
boolean required = determineRequiredStatus(ann);
currElements.add(new AutowiredFieldElement(field, required));
}
});
// 掃描所有方法
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
return;
}
// 通過分析屬於一個方法的所有註解來查找@Autowired註解
AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation is not supported on static methods: " + method);
}
return;
}
if (method.getParameterCount() == 0) {
if (logger.isWarnEnabled()) {
logger.warn("Autowired annotation should only be used on methods with parameters: " +
method);
}
}
boolean required = determineRequiredStatus(ann);
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
currElements.add(new AutowiredMethodElement(method, required, pd));
}
});
elements.addAll(0, currElements);
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class);
return new InjectionMetadata(clazz, elements);
}
populateBean(beanName, mbd, instanceWrapper)
/**
* 給已經已經初始化的屬性賦值,包括完成bean的依賴注入
* 這個方法最重要就是最後一個方法applyPropertyValues(beanName, mbd, bw, pvs):爲屬性賦值
*/
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
// 這一大段代碼省略
......
// 爲屬性賦值
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
applyPropertyValues(beanName, mbd, bw, pvs)
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
// 這一大段代碼省略
......
// 爲當前bean中屬性賦值,包括依賴注入的屬性
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
// 這一大段代碼省略
......
}
valueResolver.resolveValueIfNecessary(pv, originalValue)
/**
* 如果當前初始化的bean有屬性需要注入的,將會調用resolveReference(argName, ref)來返回需要注入的bean
*/
public Object resolveValueIfNecessary(Object argName, @Nullable Object value) {
// 獲取需要依賴注入屬性的值
if (value instanceof RuntimeBeanReference) {
RuntimeBeanReference ref = (RuntimeBeanReference) value;
return resolveReference(argName, ref);
}
// 這一大段代碼省略
......
}
resolveReference(argName, ref)
private Object resolveReference(Object argName, RuntimeBeanReference ref) {
try {
Object bean;
String refName = ref.getBeanName();
refName = String.valueOf(doEvaluate(refName));
if (ref.isToParent()) {
if (this.beanFactory.getParentBeanFactory() == null) {
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Can't resolve reference to bean '" + refName +
"' in parent factory: no parent factory available");
}
bean = this.beanFactory.getParentBeanFactory().getBean(refName);
}
else {
// 當前初始化bean主要爲屬性注入另外一個bean,調用getBean()方法獲取需要注入的bean,最終注入到屬性中
bean = this.beanFactory.getBean(refName);
this.beanFactory.registerDependentBean(refName, this.beanName);
}
if (bean instanceof NullBean) {
bean = null;
}
return bean;
}
catch (BeansException ex) {
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
}
}
getSingleton(beanName, singletonFactory)
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
// 嘗試從一級緩存中獲取bean實例
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 + "'");
}
// 將beanName添加到singletonsCurrentlyInCreation集合中,
// 用於表明beanName對應的bean正在創建中
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
// 調用FactoryBean接口中的getObject()方法獲取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;
}
// 從singletonsCurrentlyInCreation實現FactoryBean接口中的bean,表明實現了FactoryBean接口的bean獲取完畢
afterSingletonCreation(beanName);
}
if (newSingleton) {
// 最後將singletonObject添加到singletonObjects一級緩存中,同時將二級、三級緩存中的bean刪除
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
addSingleton(beanName, singletonObject)
/**
* 將singletonObject添加到singletonObjects一級緩存中,同時將二級、三級緩存中的bean刪除
*/
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);
}
}