• spring IoC 二 实例化(instant)、初始化(init)


    接着上一篇

    AbstractAutowireCapableBeanFactory中createBean方法:

     2     protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
     3         if (logger.isDebugEnabled()) {
     4             logger.debug("Creating instance of bean '" + beanName + "'");
     5         }
     6         // Make sure bean class is actually resolved at this point.
     7         resolveBeanClass(mbd, beanName);
     8 
     9         // Prepare method overrides.
    10         try {
    11             mbd.prepareMethodOverrides();
    12         }
    13         catch (BeanDefinitionValidationException ex) {
    14             throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
    15                     beanName, "Validation of method overrides failed", ex);
    16         }
    17 
    18         try {
    19             // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
    20 Object bean = resolveBeforeInstantiation(beanName, mbd); 21 if (bean != null) { 22 return bean; 23 } 24 } 25 catch (Throwable ex) { 26 throw new BeanCreationException(mbd.getResourceDescription(), beanName, 27 "BeanPostProcessor before instantiation of bean failed", ex); 28 } 29 30 Object beanInstance = doCreateBean(beanName, mbd, args); 31 if (logger.isDebugEnabled()) { 32 logger.debug("Finished creating instance of bean '" + beanName + "'"); 33 } 34 return beanInstance; 35 }

    ①resolveBeforeInstantiation方法  作用Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.

    该方法中用到  resolveBeforeInstantiation--->applyBeanPostProcessorsBeforeInstantiation--->InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation(实例前处理)

    ②doCreateBean如下

    AbstractAutowireCapableBeanFactory中doCreateBean方法

     1     protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
     2         // Instantiate the bean.
     3         BeanWrapper instanceWrapper = null;
     4         if (mbd.isSingleton()) {
     5             instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
     6         }
     7         if (instanceWrapper == null) {
     8             instanceWrapper = createBeanInstance(beanName, mbd, args);
     9         }
    10         final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
    11         Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
    12 
    13         // Allow post-processors to modify the merged bean definition.
    14         synchronized (mbd.postProcessingLock) {
    15             if (!mbd.postProcessed) {
    16                 applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
    17                 mbd.postProcessed = true;
    18             }
    19         }
    20 
    21         // Eagerly cache singletons to be able to resolve circular references
    22         // even when triggered by lifecycle interfaces like BeanFactoryAware.
    23         boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
    24                 isSingletonCurrentlyInCreation(beanName));
    25         if (earlySingletonExposure) {
    26             if (logger.isDebugEnabled()) {
    27                 logger.debug("Eagerly caching bean '" + beanName +
    28                         "' to allow for resolving potential circular references");
    29             }
    30             addSingletonFactory(beanName, new ObjectFactory<Object>() {
    31                 public Object getObject() throws BeansException {
    32                     return getEarlyBeanReference(beanName, mbd, bean);
    33                 }
    34             });
    35         }
    36 
    37         // Initialize the bean instance.
    38         Object exposedObject = bean;
    39         try {
    40             populateBean(beanName, mbd, instanceWrapper);
    41             if (exposedObject != null) {
    42                 exposedObject = initializeBean(beanName, exposedObject, mbd);
    43             }
    44         }
    45         catch (Throwable ex) {
    46             if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
    47                 throw (BeanCreationException) ex;
    48             }
    49             else {
    50                 throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
    51             }
    52         }
    53 
    54         if (earlySingletonExposure) {
    55             Object earlySingletonReference = getSingleton(beanName, false);
    56             if (earlySingletonReference != null) {
    57                 if (exposedObject == bean) {
    58                     exposedObject = earlySingletonReference;
    59                 }
    60                 else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
    61                     String[] dependentBeans = getDependentBeans(beanName);
    62                     Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
    63                     for (String dependentBean : dependentBeans) {
    64                         if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
    65                             actualDependentBeans.add(dependentBean);
    66                         }
    67                     }
    68                     if (!actualDependentBeans.isEmpty()) {
    69                         throw new BeanCurrentlyInCreationException(beanName,
    70                                 "Bean with name '" + beanName + "' has been injected into other beans [" +
    71                                 StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
    72                                 "] in its raw version as part of a circular reference, but has eventually been " +
    73                                 "wrapped. This means that said other beans do not use the final version of the " +
    74                                 "bean. This is often the result of over-eager type matching - consider using " +
    75                                 "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
    76                     }
    77                 }
    78             }
    79         }
    80 
    81         // Register bean as disposable.
    82         try {
    83             registerDisposableBeanIfNecessary(beanName, bean, mbd);
    84         }
    85         catch (BeanDefinitionValidationException ex) {
    86             throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    87         }
    88 
    89         return exposedObject;
    90     }

    其中

    ①createBeanInstance  Bean实例化,工厂、jvm、cglib生成

    ②populateBean 依赖注入 包括 autowire_by_name、autowire_by_type,其中调用了InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation(实例后处理)

    ③initializeBean 初始化    invokeAwareMethods、applyBeanPostProcessorsBeforeInitialization-->BeanPostProcessor.postProcessBeforeInitialization(初始化前处理)

    invokeInitMethods(afterPropertiesSet    invokeCustomInitMethod自定义init)、applyBeanPostProcessorsAfterInitialization-->BeanPostProcessor.postProcessAfterInitialization(初始化后处理)

  • 相关阅读:
    分享
    慕课网-软件测试基础-学习笔记
    向量内积(点乘)和外积(叉乘)概念及几何意义
    使用opencv3+python实现视频运动目标检测
    解决opencv3运行opencv2代码时报错的修改备忘录
    分享
    OpenCV学习笔记
    LeetCode
    LeetCode
    npm安装包很慢
  • 原文地址:https://www.cnblogs.com/toUpdating/p/9726300.html
Copyright © 2020-2023  润新知