static { try { javaxInjectProviderClass = ClassUtils.forName("javax.inject.Provider", DefaultListableBeanFactory.class.getClassLoader()); } catch (ClassNotFoundException ex) { // JSR-330 API not available - Provider interface simply not supported then. javaxInjectProviderClass = null; } }
/** * Map from serialized id to factory instance. */ privatestaticfinal Map<String, Reference<DefaultListableBeanFactory>> serializableFactories = new ConcurrentHashMap<>(8);
/** * Optional id for this factory, for serialization purposes. */ @Nullable private String serializationId;
/** * Whether to allow re-registration of a different definition with the same name. */ privateboolean allowBeanDefinitionOverriding = true;
/** * Whether to allow eager class loading even for lazy-init beans. */ privateboolean allowEagerClassLoading = true;
/** * Optional OrderComparator for dependency Lists and arrays. */ @Nullable private Comparator<Object> dependencyComparator;
/** * Resolver to use for checking if a bean definition is an autowire candidate. */ private AutowireCandidateResolver autowireCandidateResolver = SimpleAutowireCandidateResolver.INSTANCE;
/** * Map from dependency type to corresponding autowired value. * 缓存 类型对应的自动装载的Bean */ privatefinal Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16);
/** * Map of bean definition objects, keyed by bean name. * 缓存 beanName到BeanDefinition的映射关系 */ privatefinal Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
/** * Map from bean name to merged BeanDefinitionHolder. */ privatefinal Map<String, BeanDefinitionHolder> mergedBeanDefinitionHolders = new ConcurrentHashMap<>(256);
/** * Map of singleton and non-singleton bean names, keyed by dependency type. * 缓存 类型 和 beanName的映射关系 */ privatefinal Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64);
/** * Map of singleton-only bean names, keyed by dependency type. * 缓存 类型 和 单例Bean names的映射 */ privatefinal Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64);
/** * List of bean definition names, in registration order. * 缓存 beanDefinition name的list */ privatevolatile List<String> beanDefinitionNames = new ArrayList<>(256);
/** * Maximum number of suppressed exceptions to preserve. */ privatestaticfinalint SUPPRESSED_EXCEPTIONS_LIMIT = 100;
/** * Cache of singleton objects: bean name to bean instance. * 缓存 单例对象,最终存储单例bean的map */ privatefinal Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** * Cache of singleton factories: bean name to ObjectFactory. * 缓存 单例工厂 */ privatefinal Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** * Cache of early singleton objects: bean name to bean instance. * 已经注册的单例对象集合,按照注册顺序排序的,并且是不可重复的。 */ privatefinal Map<String, Object> earlySingletonObjects = new HashMap<>(16);
// Destroy already created singletons to avoid dangling resources. destroyBeans();
// Reset 'active' flag. cancelRefresh(ex);
// Propagate exception to caller. throw ex; }
finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
// Eagerly check singleton cache for manually registered singletons. // 先从缓存中取的Bean,处理哪些已经被创建的单例模式Bean 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 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)) { thrownew BeanCurrentlyInCreationException(beanName); }
// Check if bean definition exists in this factory. // 检查BeanDefinition,不存在从双亲BeanFactory获取 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); } elseif (args != null) { // Delegation to parent with explicit args. return (T) parentBeanFactory.getBean(nameToLookup, args); } elseif (requiredType != null) { // No args -> delegate to standard getBean method. return parentBeanFactory.getBean(nameToLookup, requiredType); } else { return (T) parentBeanFactory.getBean(nameToLookup); } }
if (!typeCheckOnly) { markBeanAsCreated(beanName); }
// 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.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); }
if (earlySingletonExposure) { Object earlySingletonReference = getSingleton(beanName, false); if (earlySingletonReference != null) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } elseif (!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()) { thrownew 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 " + "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example."); } } } }
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args){ // Make sure bean class is actually resolved at this point. Class<?> beanClass = resolveBeanClass(mbd, beanName);
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) { thrownew BeanCreationException(mbd.getResourceDescription(), beanName, "Bean class isn't public, and non-public access not allowed: " + beanClass.getName()); }
protectedvoidpopulateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw){ if (bw == null) { if (mbd.hasPropertyValues()) { thrownew 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. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { return; } } } }
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); // 这里开始进行依赖注入过程,先处理autowire的注入 int resolvedAutowireMode = mbd.getResolvedAutowireMode(); if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { MutablePropertyValues newPvs = new MutablePropertyValues(pvs); // Add property values based on autowire by name if applicable. // 这里对autowire注入过程,可以根据bean的名称或者类型来完成bean的自动注入 if (resolvedAutowireMode == AUTOWIRE_BY_NAME) { autowireByName(beanName, mbd, bw, newPvs); } // Add property values based on autowire by type if applicable. if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) { autowireByType(beanName, mbd, bw, newPvs); } pvs = newPvs; }