Spring 源码之 Bean的创建(二)

12 阅读10分钟

refresh-07:initMessageSource

protected void initMessageSource() {    // 获取bean工厂,一般是DefaultListableBeanFactory    ConfigurableListableBeanFactory beanFactory = getBeanFactory();    // 首先判断是否已有xml文件定义了id为messageSource的bean对象    if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {      // 如果有,则从BeanFactory中获取这个对象      this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);      // Make MessageSource aware of parent MessageSource.      // 当父类bean工厂不为空,并且这个bean对象是HierarchicalMessageSource类型      if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {        // 类型强制转换,转换为HierarchicalMessageSource的类型        HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;        // 判断父类的messageSource是否为空,如果等于空,则设置父类的messageSource        if (hms.getParentMessageSource() == null) {          // Only set parent context as parent MessageSource if no parent MessageSource          // registered already.          hms.setParentMessageSource(getInternalParentMessageSource());        }      }      if (logger.isTraceEnabled()) {        logger.trace("Using MessageSource [" + this.messageSource + "]");      }    }    else {      // Use empty MessageSource to be able to accept getMessage calls.      // 如果没有xml文件定义信息源对象,新建DelegatingMessageSource类作为messageSource的bean      DelegatingMessageSource dms = new DelegatingMessageSource();      // 给这个DelegatingMessageSource添加父类消息源      dms.setParentMessageSource(getInternalParentMessageSource());      this.messageSource = dms;      // 将这个messageSource实例注册到bean工厂中      beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);      if (logger.isTraceEnabled()) {        logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");      }    }  }

refresh-08:initApplicationEventMulticaster

protected void initApplicationEventMulticaster() {    // 获取当前bean工厂,一般是DefaultListableBeanFactory    ConfigurableListableBeanFactory beanFactory = getBeanFactory();    // 判断容器中是否存在bdName为applicationEventMulticaster的bd,也就是说自定义的事件监听多路广播器,必须实现ApplicationEventMulticaster接口    if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {      // 如果有,则从bean工厂得到这个bean对象      this.applicationEventMulticaster =          beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);      if (logger.isTraceEnabled()) {        logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");      }    }    else {      // 如果没有,则默认采用SimpleApplicationEventMulticaster      this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);      beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);      if (logger.isTraceEnabled()) {        logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +            "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");      }    }  }

refresh-09

子类扩展实现

refresh-10:registerListeners,注册监听器

protected void registerListeners() {   // Register statically specified listeners first.   // 遍历监听器集合,添加到广播器中   for (ApplicationListener<?> listener : getApplicationListeners()) {      getApplicationEventMulticaster().addApplicationListener(listener);   }   // Do not initialize FactoryBeans here: We need to leave all regular beans   // uninitialized to let post-processors apply to them!   // 从容器获取所有实现ApplicationListener接口的beaname   String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);   for (String listenerBeanName : listenerBeanNames) {      getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);   }   // Publish early application events now that we finally have a multicaster...   // 发布早期监听器   Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;   this.earlyApplicationEvents = null;   if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {      for (ApplicationEvent earlyEvent : earlyEventsToProcess) {         getApplicationEventMulticaster().multicastEvent(earlyEvent);      }   }}

refresh-11:finishBeanFactoryInitialization,创建单例bean

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 BeanFactoryPostProcessor   // (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:   // at this point, primarily for resolution in annotation attribute values.   // 嵌入值解析器   if (!beanFactory.hasEmbeddedValueResolver()) {      beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));   }   // 初始化loadTimeWeaverAware bean   // 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);   // 冻结bean定义   // Allow for caching all bean definition metadata, not expecting further changes.   beanFactory.freezeConfiguration();   // 实例化   // Instantiate all remaining (non-lazy-init) singletons.   beanFactory.preInstantiateSingletons();}

真正开始创建bean:beanFactory.preInstantiateSingletons();

创建bean涉及到的方法

getBean

doGetBean

createBean

doCreateBean

createBeanInstance

populateBean

initializeBean

DefaultListableBeanFactory

public void preInstantiateSingletons() throws BeansException {   if (logger.isTraceEnabled()) {      logger.trace("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<>(this.beanDefinitionNames);    // 触发所有非延迟加载单例bean    // Trigger initialization of all non-lazy singleton beans...    for (String beanName : beanNames) {      // 合并父类BeanDefinition      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);      // 非抽象、单例、非懒加载      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {        // 是否实现FactoryBean接口,面试点:FactoryBean和BeanFactory区别        if (isFactoryBean(beanName)) {          Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);          if (bean instanceof FactoryBean) {            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 {          // 非factoryBean          getBean(beanName);        }      }    }    // 出发所有SmartInitializingSingleton回调    // Trigger post-initialization callback for all applicable beans...    for (String beanName : beanNames) {      Object singletonInstance = getSingleton(beanName);      if (singletonInstance instanceof SmartInitializingSingleton) {        SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;        if (System.getSecurityManager() != null) {          AccessController.doPrivileged((PrivilegedAction<Object>) () -> {            smartSingleton.afterSingletonsInstantiated();            return null;          }, getAccessControlContext());        } else {          smartSingleton.afterSingletonsInstantiated();        }      }    }}

getBean:直接调用doGetBean

protected <T> T doGetBean(      String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)      throws BeansException {   // 对应beanName,为什么不能直接使用?因为实现beanFacotry和别名,名称特殊,进行转换   String beanName = transformedBeanName(name);   Object bean;   // 检查单例缓存是否有单例对象,循环依赖关联   // Eagerly check singleton cache for manually registered singletons.   Object sharedInstance = getSingleton(beanName);   // bean找到,没有创建对象参数   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 = 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 (parentBeanFactory instanceof AbstractBeanFactory) {            // 递归调用父容器dogetbean            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 if (requiredType != null) {            // No args -> delegate to standard getBean method.            return parentBeanFactory.getBean(nameToLookup, requiredType);         }         else {            return (T) parentBeanFactory.getBean(nameToLookup);         }      }      // 不做类型检查,表示要创建bean      if (!typeCheckOnly) {         // 标记已创建         markBeanAsCreated(beanName);      }      try {         // xml中为GenericBeanDefinition         // 如果子类bean会合并父类属性         RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);         // 校验合法性         checkMergedBeanDefinition(mbd, beanName, args);         // 有依赖,优先创建依赖bean         // Guarantee initialization of beans that the current bean depends on.         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 + "'");               }               // 注册bean依赖关系               registerDependentBean(dep, beanName);               try {                  // 递归实例化依赖bean                  getBean(dep);               }               catch (NoSuchBeanDefinitionException ex) {                  throw new BeanCreationException(mbd.getResourceDescription(), beanName,                        "'" + beanName + "' depends on missing bean '" + dep + "'", ex);               }            }         }         // Create bean instance.         if (mbd.isSingleton()) {            sharedInstance = getSingleton(beanName, () -> {               try {                  // 创建bean                  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);         }         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);         }         else {            String scopeName = mbd.getScope();            if (!StringUtils.hasLength(scopeName)) {               throw new IllegalStateException("No scope name defined for bean '" + beanName + "'");            }            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.isTraceEnabled()) {            logger.trace("Failed to convert bean '" + name + "' to required type '" +                  ClassUtils.getQualifiedName(requiredType) + "'", ex);         }         throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());      }   }   return (T) bean;}

createBean

protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)      throws BeanCreationException {   if (logger.isTraceEnabled()) {      logger.trace("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.   Class<?> resolvedClass = resolveBeanClass(mbd, beanName);   if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {      mbdToUse = new RootBeanDefinition(mbd);      mbdToUse.setBeanClass(resolvedClass);   }   // 覆盖方法 lookup-method replace-method   // Prepare method overrides.   try {      mbdToUse.prepareMethodOverrides();   }   catch (BeanDefinitionValidationException ex) {      throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),            beanName, "Validation of method overrides failed", ex);   }   try {      // 自定义BeanPostProcessors,返回一个实例对象      // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.      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);   }   try {      // 创建bean      Object beanInstance = doCreateBean(beanName, mbdToUse, args);      if (logger.isTraceEnabled()) {         logger.trace("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);   }}

doCreateBean

protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)      throws BeanCreationException {   // 创建的bean被包装的类型   // Instantiate the bean.   BeanWrapper instanceWrapper = null;   if (mbd.isSingleton()) {      instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);   }   if (instanceWrapper == null) {      // 创建实例对象,简单实例;      // 实例化bean方式有哪些?      instanceWrapper = createBeanInstance(beanName, mbd, args);   }   // 获取bean   Object bean = instanceWrapper.getWrappedInstance();   Class<?> beanType = instanceWrapper.getWrappedClass();   if (beanType != NullBean.class) {      mbd.resolvedTargetType = beanType;   }   // Allow post-processors to modify the merged bean definition.   // 允许bpp修改合并的bd   synchronized (mbd.postProcessingLock) {      if (!mbd.postProcessed) {         try {            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正在创建中,检测循环依赖   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");      }      // 避免循环依赖,在bean初始化前创建的实例加入工厂      // 放至三级缓存,放的是lamada表达式      addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));   }   // Initialize the bean instance.   Object exposedObject = bean;   try {      // 属性填充,可能依赖其他bean,会递归创建bean      populateBean(beanName, mbd, instanceWrapper);      // 初始化逻辑,包括bpp      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)) {            // 因为bean创建后所依赖的bean一定是已经创建的            // actualDependentBeans不为空则表示当前bean创建后其依赖的bean却没有全部创建完,也就是说存在循环依赖            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 " +                     "'getBeanNamesForType' 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;}

createBeanInstance:实例化bean;这块就能看到实例化bean的方式都有哪些?

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);   // 类不为空为public   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());   }   // 判断当前beanDefinition中是否包含实例supplier : 一种   Supplier<?> instanceSupplier = mbd.getInstanceSupplier();   if (instanceSupplier != null) {      return obtainFromSupplier(instanceSupplier, beanName);   }   // 工厂方法: 二种   if (mbd.getFactoryMethodName() != null) {      return instantiateUsingFactoryMethod(beanName, mbd, args);   }   // 根据参数、类型选择合适构造器   // Shortcut when re-creating the same bean...   boolean resolved = false;   boolean autowireNecessary = false;   if (args == null) {      synchronized (mbd.constructorArgumentLock) {         // 确定好的构造器缓存起来,方便下次直接使用:RootBeanDefinition中的属性resolvedConstructorOrFactoryMethod         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?   // 有构造方法 || 自动装配为构造函数 || bd设置构造参数值 || 有构造函数参数列表   Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);   if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||         mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {      return autowireConstructor(beanName, mbd, ctors, args);   }   // 找出合适的默认构造方法   // Preferred constructors for default construction?   ctors = mbd.getPreferredConstructors();   if (ctors != null) {      return autowireConstructor(beanName, mbd, ctors, null);   }   // 默认无参构造   // No special handling: simply use no-arg constructor.   return instantiateBean(beanName, mbd);}

populuteBean:主要处理三部分:byName、byType、autowired注入

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {   if (bw == null) {      // 有需要设置的属性      if (mbd.hasPropertyValues()) {         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.   // synthetic:false(aop或者advice才会设置true)   // 有InstantiationAwareBeanPostProcessor:用于设置属性   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);   // 装配模式:名称、类型   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.      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);      }      // newPvs包含pvs以及通过自动装配所得到的值      pvs = newPvs;   }   boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();   boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);   PropertyDescriptor[] filteredPds = null;   if (hasInstAwareBpps) {      if (pvs == null) {         pvs = mbd.getPropertyValues();      }      // 通过遍历AutowiredAnnotationBeanPostProcessore执行postProcessProssor方法实现@Autowire都注解      for (BeanPostProcessor bp : getBeanPostProcessors()) {         if (bp instanceof InstantiationAwareBeanPostProcessor) {            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;            PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);            if (pvsToUse == null) {               if (filteredPds == null) {                  // 筛选                  filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);               }               pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);               if (pvsToUse == null) {                  return;               }            }            pvs = pvsToUse;         }      }   }   if (needsDepCheck) {      if (filteredPds == null) {         filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);      }      checkDependencies(beanName, mbd, filteredPds, pvs);   }   if (pvs != null) {      // 给定属性绑定对象中      applyPropertyValues(beanName, mbd, bw, pvs);   }}

initializeBean:涉及4个方法,aware bpp.before init-method bpp.after

protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {   if (System.getSecurityManager() != null) {      AccessController.doPrivileged((PrivilegedAction<Object>) () -> {         invokeAwareMethods(beanName, bean);         return null;      }, getAccessControlContext());   }   else {      // Aware接口      invokeAwareMethods(beanName, bean);   }   Object wrappedBean = bean;   if (mbd == null || !mbd.isSynthetic()) {      // bpp.before      wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);   }   try {      // 初始方法      // 先调用InitializingBean(afterPropertiesSet:方法)接口 后调用自定义方法      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()) {      // bpp.after : aop实现在此处      wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);   }   return wrappedBean;}

refresh-12:finishRefresh()

主要清除资源缓存,发布最终事件,支持jmx服务的类


到此,Spring bean 创建过程大体梳理完,由于篇幅有限,后续会有总结文章,补充bean 创建过程中涉及的核心方法详细分析、循环依赖、扩展点、重要的类;当前也会通过新的文章来从源码角度分析**AOP**是如何实现的。

来自公众号:一个程序猿的笔记