博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring初始化容器—实例化bean对象
阅读量:7033 次
发布时间:2019-06-28

本文共 14347 字,大约阅读时间需要 47 分钟。

hot3.png

        通过AbstractApplicationContext.refresh()方法调用finishBeanFactoryInitialization()方法进行bean的创建。

/** * 完成bean的创建 * Finish the initialization of this context's bean factory, * initializing all remaining singleton beans. */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));   }   // 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();   //主要完成bean对象的实例化   // Instantiate all remaining (non-lazy-init) singletons.   beanFactory.preInstantiateSingletons();}

        DefaultListableBeanFactory:主要完成bean的实例化、以及存储XmlBeanDefinitionReader解析resource注册到beanFactory中的BeanDefinition;数据结构如下:

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory      implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {  //.........................    //存储由XmlBeanDefinitionReader解析资源文件中的BeanDefinition   /** Map of bean definition objects, keyed by bean name */   private final Map
 beanDefinitionMap = new ConcurrentHashMap
(64);   /** Map of singleton and non-singleton bean names keyed by dependency type */   private final Map
, String[]> allBeanNamesByType = new ConcurrentHashMap
, String[]>(64);   /** Map of singleton-only bean names keyed by dependency type */   private final Map
, String[]> singletonBeanNamesByType = new ConcurrentHashMap
, String[]>(64);   /** List of bean definition names, in registration order */   private final List
 beanDefinitionNames = new ArrayList
();   /** Whether bean definition metadata may be cached for all beans */   private boolean configurationFrozen = false;   /** Cached array of bean definition names in case of frozen configuration */   private String[] frozenBeanDefinitionNames;      //.....................}

        初始化单列bean对象,其中bean对象包括普通的bean对象和实现FactoryBean接口的bean对象;通过beanFactory获取FactoryBean对应的bean对象实际是通过FactoryBean.getObject()方法获取的。

@Overridepublic void preInstantiateSingletons() throws BeansException {   if (this.logger.isDebugEnabled()) {      this.logger.debug("Pre-instantiating singletons in " + this);   }   List
 beanNames;   synchronized (this.beanDefinitionMap) {      // 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.      beanNames = new ArrayList
(this.beanDefinitionNames);   }   for (String beanName : beanNames) {      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {         //判断bean类型         if (isFactoryBean(beanName)) {            //获取FactoryBean本身需要前缀“&”            final FactoryBean
 factory = (FactoryBean
) getBean(FACTORY_BEAN_PREFIX + beanName);            boolean isEagerInit;            if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {               isEagerInit = AccessController.doPrivileged(new PrivilegedAction
() {                  @Override                  public Boolean run() {                     return ((SmartFactoryBean
) factory).isEagerInit();                  }               }, getAccessControlContext());            }            else {               isEagerInit = (factory instanceof SmartFactoryBean &&                     ((SmartFactoryBean
) factory).isEagerInit());            }            if (isEagerInit) {               getBean(beanName);            }         }         else {//普通bean的创建            getBean(beanName);         }      }   }}/** * Return an instance, which may be shared or independent, of the specified bean. * @param name the name of the bean to retrieve  * @param requiredType the required type of the bean to retrieve bean类型 * @param args arguments to use if creating a prototype using explicit arguments to a * static factory method. It is invalid to use a non-null args value in any other case.  * args是prototype所需的参数 * @param typeCheckOnly whether the instance is obtained for a type check, 是否是类型检查 * not for actual use * @return an instance of the bean * @throws BeansException if the bean could not be created */@SuppressWarnings("unchecked")protected 
 T doGetBean(      final String name, final Class
 requiredType, final Object[] args, boolean typeCheckOnly)      throws BeansException {   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.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 = 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 (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) {         markBeanAsCreated(beanName);//标记bean已创建      }      try {         //获取BeanDefinition         final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);         //检查BeanDefinition是否是Abstract,或者是否是Prototype等处理         checkMergedBeanDefinition(mbd, beanName, args);         //获取bean的依赖         // Guarantee initialization of beans that the current bean depends on.         String[] dependsOn = mbd.getDependsOn();         if (dependsOn != null) {            for (String dependsOnBean : dependsOn) {               //判断循环依赖               if (isDependent(beanName, dependsOnBean)) {                  throw new BeanCreationException("Circular depends-on relationship between '" +                        beanName + "' and '" + dependsOnBean + "'");               }               registerDependentBean(dependsOnBean, beanName);               getBean(dependsOnBean);            }         }         //1、创建SingleBean         // Create bean instance.         if (mbd.isSingleton()) {             //创建单实例bean            sharedInstance = getSingleton(beanName, new ObjectFactory
() {               @Override               public Object getObject() throws BeansException {                  try {                     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);         }         //2、创建PrototypeBean         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对象,bean为FactoryBean类型则,通过FactoryBean.getObject()获取,反之直接返回            //prototypeInstance            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 '" + scopeName + "'");            }            try {               Object scopedInstance = scope.get(beanName, new ObjectFactory() {                  @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;      }   }   //classType检查,若bean来下与ClassType不同,则进行强制转换   // Check if required type matches the type of the actual bean instance.   if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {      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;}1、创建单实例bean,主要是依赖其父类SingletonBeanRegistry实现;SingletonBeanRegistry数据结构:public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {   /**    * Internal marker for a null singleton object:    * used as marker value for concurrent Maps (which don't support null values).    */   protected static final Object NULL_OBJECT = new Object();       //缓存singleton对象   private final Map
 singletonObjects = new ConcurrentHashMap
(64);   //缓存beanFactory   /** Cache of singleton factories: bean name --> ObjectFactory */   private final Map
> singletonFactories = new HashMap
>(16);   //缓存earlySingletonObjects,缓存创建的bean之前是否已被缓存过   /** Cache of early singleton objects: bean name --> bean instance */   private final Map
 earlySingletonObjects = new HashMap
(16);   //缓存所有注册过的beanName   /** Set of registered singletons, containing the bean names in registration order */   private final Set
 registeredSingletons = new LinkedHashSet
(64);   //当前正被创建的beanName   /** Names of beans that are currently in creation */   private final Set
 singletonsCurrentlyInCreation =         Collections.newSetFromMap(new ConcurrentHashMap
(16));   //创建被排除的beanname   /** Names of beans currently excluded from in creation checks */   private final Set
 inCreationCheckExclusions =         Collections.newSetFromMap(new ConcurrentHashMap
(16));   /** List of suppressed Exceptions, available for associating related causes */   private Set
 suppressedExceptions;   /** Flag that indicates whether we're currently within destroySingletons */   private boolean singletonsCurrentlyInDestruction = false;   /** Disposable bean instances: bean name --> disposable instance */   private final Map
 disposableBeans = new LinkedHashMap
();   /** Map between containing bean names: bean name --> Set of bean names that the bean contains */   private final Map
> containedBeanMap = new ConcurrentHashMap
>(16);   //缓存当前bean被所有其他bean依赖的集合   /** Map between dependent bean names: bean name --> Set of dependent bean names */   private final Map
> dependentBeanMap = new ConcurrentHashMap
>(64);   //与dependentBeanMap缓存方式相反,缓存当前bean所依赖的所有其他bean的集合   /** Map between depending bean names: bean name --> Set of bean names for the bean's dependencies */   private final Map
> dependenciesForBeanMap = new ConcurrentHashMap
>(64);     //..........................method............../** * Return the (raw) singleton object registered under the given name, * creating and registering a new one if none registered yet. * @param beanName the name of the bean * @param singletonFactory the ObjectFactory to lazily create the singleton * with, if necessary * @return the registered singleton object */public Object getSingleton(String beanName, ObjectFactory
 singletonFactory) {   Assert.notNull(beanName, "'beanName' must not be null");   synchronized (this.singletonObjects) {      Object singletonObject = this.singletonObjects.get(beanName);      if (singletonObject == null) {         if (this.singletonsCurrentlyInDestruction) {            throw new BeanCreationNotAllowedException(beanName,                  "Singleton bean creation not allowed while the 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 + "'");         }         beforeSingletonCreation(beanName);         boolean recordSuppressedExceptions = (this.suppressedExceptions == null);         if (recordSuppressedExceptions) {            this.suppressedExceptions = new LinkedHashSet
();         }         try {            //创建bean            singletonObject = singletonFactory.getObject();         }         catch (BeanCreationException ex) {            if (recordSuppressedExceptions) {               for (Exception suppressedException : this.suppressedExceptions) {                  ex.addRelatedCause(suppressedException);               }            }            throw ex;         }         finally {            if (recordSuppressedExceptions) {               this.suppressedExceptions = null;            }            afterSingletonCreation(beanName);         }         //将以创建的bean加入缓存singletonObjects中         addSingleton(beanName, singletonObject);      }      return (singletonObject != NULL_OBJECT ? singletonObject : null);   }}}

转载于:https://my.oschina.net/u/1263326/blog/534155

你可能感兴趣的文章
利用JDK1.5的工具对远程的Java应用程序进行监测(摘录)
查看>>
开源实时消息推送系统 MPush
查看>>
Azure Automation (4) 按照Azure虚拟机的机器名,设置开关机
查看>>
二维数组排序
查看>>
【Shell脚本】自动ssh登录重启Apache
查看>>
android:onClick vs setOnClickListener
查看>>
系统启动失败之bois设置
查看>>
[3d跑酷] Xcode5 打包 发布配置
查看>>
Objective-C:ARC自动释放对象内存
查看>>
php 简易验证码(GD库)
查看>>
[LeetCode] Linked List Cycle 单链表中的环
查看>>
JS兼容所有浏览器的一段加入收藏代码,设置为首页
查看>>
MapGuide / Map 3D 开发常用资料链接
查看>>
从图纸到Web互联网—Map3D、MapGuide在地图电子中的应用【译】
查看>>
程序员职业发展的绊脚石-思想的枷锁
查看>>
在vscode中使用pylint-django插件解决pylint的一些不必要的错误提示【转】
查看>>
ARM-Linux (临时,正式) 建立页表的比较【转】
查看>>
Android -- 程序启动画面 Splash
查看>>
C++中四种显示类型转换总结
查看>>
In_interrupt( ) 和In_irq( )【转】
查看>>