AnnotationConfigApplicationContext 启动流程

通常我们使用以下语句启用一个ioc容器 那么这段代码内部是怎么实现的呢?

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);

一. AnnotationConfigApplicationContext 类图

主要关注AnootationConfigApplicationContext 继承GenericApplicationContext 并创建了默认的beanFactory DefaultListableBeanFactory

二. 构造函数this()

this() :

1. 调用AnnotationConfigApplicationContext无参构造器

2. 调用父类GenericApplicationContext 无参构造器 实例化DefaultListableBeanFactory

3. 实例化AnnotatedBeanDefinitionReader 用于解析bean的注解信息

4.实例化ClassPathBeanDefinitionScanner

public AnnotationConfigApplicationContext(Class... annotatedClasses) {

 // 调用无参构造器
 // 父类 GenericApplicationContext 实例化了 DefaultListableBeanFactory

   this();

   // 注册配置类 

   register(annotatedClasses);

    // 刷新ioc容器

   refresh();

}

public GenericApplicationContext() {  
  //调用父类的无参构造器  创建了默认的DefaultListableBeanFactory
   this.beanFactory = new DefaultListableBeanFactory();
}


public AnnotationConfigApplicationContext() {

//初始化了AnnotatedBeanDefinitionReader 和ClassPathBeanDefinitionScanner

   this.reader = new AnnotatedBeanDefinitionReader(this);

   this.scanner = new ClassPathBeanDefinitionScanner(this);

}


三.  register(annotatedClasses) 注册配置类

1. 调用上一流程初始化的AnnotatedBeanDefinitionReader 的register方法

2.获取配置类的注解信息

3. 判断@Conditional  条件

4.判断Scope 若无则默认为单例模式

5.  在DefaultListableBeanFactory 注册一个 beanNane -> beanDefinition 的map  和alias ->  beanName 的map

public void register(Class... annotatedClasses) {

   for (Class annotatedClass : annotatedClasses) {

      registerBean(annotatedClass);

   }

}

public void registerBean(Class annotatedClass) {

   doRegisterBean(annotatedClass, null, null, null);

}

/**

* Register a bean from the given bean class, deriving its metadata from

* class-declared annotations.

* @param annotatedClass the class of the bean

* @param instanceSupplier a callback for creating an instance of the bean

* (may be {@code null})

* @param name an explicit name for the bean

* @param qualifiers specific qualifier annotations to consider, if any,

* in addition to qualifiers at the bean class level

* @param definitionCustomizers one or more callbacks for customizing the

* factory's {@link BeanDefinition}, e.g. setting a lazy-init or primary flag

核心方法 注册配置类

* @since 5.0

*/

void doRegisterBean(Class annotatedClass, @Nullable Supplier instanceSupplier, @Nullable String name,

      @Nullable Class[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {

    // 创建AnnotatedGenericBeanDefinition 配置beanClass和 metaData(注解信息)

   AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);

    //根据 @Conditional 注解 判断bean是否跳过注册

   if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {

      return;

   }

    // 设置Supplier 回调

   abd.setInstanceSupplier(instanceSupplier);

  // 解析Scope 注解 若无 则默认未singleton

   ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);

  // 设置scope 

   abd.setScope(scopeMetadata.getScopeName());

// 获取beanName

   String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));

    // 处理 lazy  DependsOn Role Description parimary 这5个注解

   AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);

    // 备案此调用qualifiers 为null  暂不讨论

   if (qualifiers != null) {

      for (Class qualifier : qualifiers) {

         if (Primary.class == qualifier) {

            abd.setPrimary(true);

         }

         else if (Lazy.class == qualifier) {

            abd.setLazyInit(true);

         }

         else {

            abd.addQualifier(new AutowireCandidateQualifier(qualifier));

         }

      }

   }

    //definitionCustomizers 也为null

   for (BeanDefinitionCustomizer customizer : definitionCustomizers) {

      customizer.customize(abd);

   }

    // 创建BeanDefinitionHolder  设置 beanDefinition beanName aliases 三个属性

   BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);

// 创建代理对象

   definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);

 // 在DefaultListableBeanFactory 注册一个 beanNane -> beanDefinition 的map  和alias ->  beanName 的map

   BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);

}

四. refresh() 刷新容器

@Override

public void refresh()throws BeansException, IllegalStateException {

synchronized (this.startupShutdownMonitor) {

// Prepare this context for refreshing.

//1. 准备刷新容器

      prepareRefresh();

      // Tell the subclass to refresh the internal bean factory.

// 2.通知子类刷新内部beanFactory 并返回DefaultListableBeanFactory

      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

      // Prepare the bean factory for use in this context.

//3.给 DefaultListableFactoryBean 赋值 例如类加载器, post processors

      prepareBeanFactory(beanFactory);

      try {

// Allows post-processing of the bean factory in context subclasses.

// 空方法 交给子类实现

        postProcessBeanFactory(beanFactory);

        // Invoke factory processors registered as beans in the context.

// 4.执行已经注册的factory processors

        invokeBeanFactoryPostProcessors(beanFactory);

        // Register bean processors that intercept bean creation.

// 5.注册BeanPostProcessor,用于拦截bean创建过程

        registerBeanPostProcessors(beanFactory);

        // Initialize message source for this context.

//初始化MessageSource组件

        initMessageSource();

        // Initialize event multicaster for this context.

      //定义事件多点广播

        initApplicationEventMulticaster();

        // Initialize other special beans in specific context subclasses.

       // 子类实现

        onRefresh();

        // Check for listener beans and register them.

       // 注册实现 org.spring.context.ApplicationListener 的bean

        registerListeners();

        // Instantiate all remaining (non-lazy-init) singletons.

//实例化所有单例类(不是懒加载)

        finishBeanFactoryInitialization(beanFactory);

        // Last step: publish corresponding event.

        finishRefresh();

      }

catch (BeansException ex) {

if (logger.isWarnEnabled()) {

logger.warn("Exception encountered during context initialization - " +

"cancelling refresh attempt: " + ex);

        }

// 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();

      }

}

}



1. prepareRefresh() 准备刷新容器

/**

* Prepare this context for refreshing, setting its startup date and

* active flag as well as performing any initialization of property sources.

*/

protected void prepareRefresh() {

// 设置启动时间

  this.startupDate = System.currentTimeMillis();

  // 设置状态

  this.closed.set(false);

  this.active.set(true);

  if (logger.isDebugEnabled()) {

if (logger.isTraceEnabled()) {

logger.trace("Refreshing " +this);

      }

else {

logger.debug("Refreshing " + getDisplayName());

      }

}

// Initialize any placeholder property sources in the context environment

// 初始化Context属性资源  空方法 交给子类实现

  initPropertySources();

  // Validate that all properties marked as required are resolvable

// see ConfigurablePropertyResolver#setRequiredProperties

// 验证需要的属性

  getEnvironment().validateRequiredProperties();

  // Allow for the collection of early ApplicationEvents,

// to be published once the multicaster is available...

// 创建一个存在早期容器时间的Set

  this.earlyApplicationEvents =new LinkedHashSet<>();

}


2. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

/**

* Tell the subclass to refresh the internal bean factory.

* @return the fresh BeanFactory instance

* @see #refreshBeanFactory()

* @see #getBeanFactory()

*/

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {

  // 设置一个序列化id

   refreshBeanFactory();

    // 返回DefaultListableBeanFactory

   return getBeanFactory();

}

/**

* Do nothing: We hold a single internal BeanFactory and rely on callers

* to register beans through our public methods (or the BeanFactory's).

* @see #registerBeanDefinition

*/

@Override

protected final void refreshBeanFactory() throws IllegalStateException {

   if (!this.refreshed.compareAndSet(false, true)) {

      throw new IllegalStateException(

            "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");

   }

   // 设置序列化ID

   this.beanFactory.setSerializationId(getId());

}

3. prepareBeanFactory(beanFactory)

给实例化的DefaultListableBeanFactory 添加默认属性 如classLoader,属性注册器,bean的后置处理器等

/**

* Configure the factory's standard context characteristics,

* such as the context's ClassLoader and post-processors.

* @param beanFactory the BeanFactory to configure

*/

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {

   // Tell the internal bean factory to use the context's class loader etc.

    // 设置classLoader  Launcher

   beanFactory.setBeanClassLoader(getClassLoader());

    // 

   beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));

    // 添加属性注册器

   beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

   // Configure the bean factory with context callbacks.

   // 添加后置处理器

   beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

    // 1. ignoreDependencyInterface的真正意思是在自动装配时忽略指定接口的实现类中,对外的依赖。 https://www.jianshu.com/p/3c7e0608ff1f

   beanFactory.ignoreDependencyInterface(EnvironmentAware.class);

   beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);

   beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);

   beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);

   beanFactory.ignoreDependencyInterface(MessageSourceAware.class);

   beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

   // BeanFactory interface not registered as resolvable type in a plain factory.

   // MessageSource registered (and found for autowiring) as a bean.

    // 设置依赖类-> 自动装配的类的映射

   beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);

   beanFactory.registerResolvableDependency(ResourceLoader.class, this);

   beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);

   beanFactory.registerResolvableDependency(ApplicationContext.class, this);

   // Register early post-processor for detecting inner beans as ApplicationListeners.

    //将早期后处理器注册为application监听器,用于检测内部bean。

   beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

   // Detect a LoadTimeWeaver and prepare for weaving, if found.

    // 添加编译时的AspectJ

   if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {

      beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));

      // Set a temporary ClassLoader for type matching.

      beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));

   }

   // Register default environment beans.

    // 设置默认的环境变量组件ConfigurableEnvironment、systemProperties、systemEnvironment

   if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {

      beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());

   }

   if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {

      beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());

   }

   if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {

      beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());

   }

}

4.  invokeBeanFactoryPostProcessors(beanFactory) 执行beanFactory后置处理器

        执行流程:

      1.根据类实现的接口(PriorityOrdered, Ordered,未实现)分离BeanDefinitionRegistryPostProcessors

         执行顺序 PriorityOrdered > Order>未实现Order接口

      2.对分离后的BeanDefinitionRegistryPostProcessors 按优先级排序(getOrder 返回的值越大 优先级越高)

     3. 执行每个BeanDefinitionRegistryPostProcessors 的postProcessBeanDefinitionRegistry方法

     4. 所有BeanDefinitionRegistryPostProcessors 分离完成且执行postProcessBeanDefinitionRegistry后  调用所有已注册的processors 的 postProcessBeanFactory方法

    5. 按同样逻辑分离分离BeanFactoryPostProcessors  (注:上面分离的是BeanDefinitionRegistryPostProcessor)

    6. 执行每个BeanFactoryPostProcessors 的 postProcessBeanFactory

        protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {

// 执行invokeBeanFactoryPostProcessors

  PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

  // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime

// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)

  if (beanFactory.getTempClassLoader() ==null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {

beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));

      beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));

  }

}

public static void invokeBeanFactoryPostProcessors(

      ConfigurableListableBeanFactory beanFactory, List beanFactoryPostProcessors) {

   // Invoke BeanDefinitionRegistryPostProcessors first, if any.

   Set processedBeans = new HashSet<>();

    // 判断是否时BeanDefinitionRegistry

   if (beanFactory instanceof BeanDefinitionRegistry) {

      BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

      List regularPostProcessors = new ArrayList<>();

      List registryProcessors = new ArrayList<>();

      for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {

         if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {

            BeanDefinitionRegistryPostProcessor registryProcessor =

                  (BeanDefinitionRegistryPostProcessor) postProcessor;

            registryProcessor.postProcessBeanDefinitionRegistry(registry);

            registryProcessors.add(registryProcessor);

         }

         else {

            regularPostProcessors.add(postProcessor);

         }

      }

      // Do not initialize FactoryBeans here: We need to leave all regular beans

      // uninitialized to let the bean factory post-processors apply to them!

      // Separate between BeanDefinitionRegistryPostProcessors that implement

      // PriorityOrdered, Ordered, and the rest.

      // 根据后置处理器实现的接口 riorityOrdered, Ordered / 普通类  分离BeanDefinitionRegistryPostProcessors 

      List currentRegistryProcessors = new ArrayList<>();

      // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.

        // 首先执行实现PriorityOrdered 的类

      String[] postProcessorNames =

            beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

        // 实例化实现PriorityOrdered 的类 

      for (String ppName : postProcessorNames) {

         if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {

            currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));

            processedBeans.add(ppName);

         }

      }

        // 根据优先级排序

      sortPostProcessors(currentRegistryProcessors, beanFactory);

      registryProcessors.addAll(currentRegistryProcessors);

      // 执行每个currentRegistryProcessors的 postProcessBeanDefinitionRegistry方法

      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);

      currentRegistryProcessors.clear();

      // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.

      // 实例化实现Ordered 的类 

      postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

      for (String ppName : postProcessorNames) {

         if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {

            currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));

            processedBeans.add(ppName);

         }

      }

      sortPostProcessors(currentRegistryProcessors, beanFactory);

      registryProcessors.addAll(currentRegistryProcessors);

      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);

      currentRegistryProcessors.clear();

      // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.

      boolean reiterate = true;

      while (reiterate) {

         reiterate = false;

         postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

         for (String ppName : postProcessorNames) {

            if (!processedBeans.contains(ppName)) {

               currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));

               processedBeans.add(ppName);

               reiterate = true;

            }

         }

         sortPostProcessors(currentRegistryProcessors, beanFactory);

         registryProcessors.addAll(currentRegistryProcessors);

         invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);

         currentRegistryProcessors.clear();

      }

      // Now, invoke the postProcessBeanFactory callback of all processors handled so far.

        // 调用所有已经注册的 processors postProcessBeanFactory

      invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);

      invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);

   }

   else {

      // Invoke factory processors registered with the context instance.

      invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);

   }

   // Do not initialize FactoryBeans here: We need to leave all regular beans

   // uninitialized to let the bean factory post-processors apply to them!

   String[] postProcessorNames =

         beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

   // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,

   // Ordered, and the rest.

   List priorityOrderedPostProcessors = new ArrayList<>();

   List orderedPostProcessorNames = new ArrayList<>();

   List nonOrderedPostProcessorNames = new ArrayList<>();

   for (String ppName : postProcessorNames) {

      if (processedBeans.contains(ppName)) {

         // skip - already processed in first phase above

      }

      else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {

         priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));

      }

      else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {

         orderedPostProcessorNames.add(ppName);

      }

      else {

         nonOrderedPostProcessorNames.add(ppName);

      }

   }

   // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.

   sortPostProcessors(priorityOrderedPostProcessors, beanFactory);

   invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

   // Next, invoke the BeanFactoryPostProcessors that implement Ordered.

   List orderedPostProcessors = new ArrayList<>();

   for (String postProcessorName : orderedPostProcessorNames) {

      orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));

   }

   sortPostProcessors(orderedPostProcessors, beanFactory);

   invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

   // Finally, invoke all other BeanFactoryPostProcessors.

   List nonOrderedPostProcessors = new ArrayList<>();

   for (String postProcessorName : nonOrderedPostProcessorNames) {

      nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));

   }

   invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

   // Clear cached merged bean definitions since the post-processors might have

   // modified the original metadata, e.g. replacing placeholders in values...

   beanFactory.clearMetadataCache();

}

5.registerBeanPostProcessors(beanFactory)注册BeanPostProcessor

1. 获取beanFactory中所有实现的beanPostProcessor

2.注册一个BeanPostProcessorChecker 来记录info信息

3.根据类实现的接口(PriorityOrdered, Ordered,未实现)分离 BeanPostProcessors ,并将MergedBeanDefinitionPostProcessor 单独归为一类

4.排序并注册

5.重新注册所有的MergedBeanDefinitionPostProcessor

6.重新注册 ApplicationListenerDetector

AbstractApplicationContext.java :

/**

* Instantiate and invoke all registered BeanPostProcessor beans,

* respecting explicit order if given.

*

Must be called before any instantiation of application beans.

* 实例化并且执行所有已经注册的的bean后置处理器,若提供顺序 则按照顺序

*/

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {

   PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);

}

PostProcessorRegistrationDelegate.java :

public static void registerBeanPostProcessors(

      ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

   String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

   // Register BeanPostProcessorChecker that logs an info message when

   // a bean is created during BeanPostProcessor instantiation, i.e. when

   // a bean is not eligible for getting processed by all BeanPostProcessors.

    // 注册一个BeanPostProcessorChecker 来记录info信息 当这个bean在BeanPostProcessor实例化期间被创建

   // 也就是一个bean不适合被所有的BeanPostProcessors所加工

   int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;

   beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

   // Separate between BeanPostProcessors that implement PriorityOrdered,

   // Ordered, and the rest.

   // 根据后置处理器实现的接口 riorityOrdered, Ordered / 普通类  分离beanPostProcessor  注 前一个流程分离的是BeanDefinitionRegistryPostProcessor

   List priorityOrderedPostProcessors = new ArrayList<>();

   List internalPostProcessors = new ArrayList<>();

   List orderedPostProcessorNames = new ArrayList<>();

   List nonOrderedPostProcessorNames = new ArrayList<>();

   for (String ppName : postProcessorNames) {

      if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {

        // 若为优先级别  则创建

         BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);

         priorityOrderedPostProcessors.add(pp);

         if (pp instanceof MergedBeanDefinitionPostProcessor) {

            internalPostProcessors.add(pp);

         }

      }

      else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {

         orderedPostProcessorNames.add(ppName);

      }

      else {

         nonOrderedPostProcessorNames.add(ppName);

      }

   }

   // First, register the BeanPostProcessors that implement PriorityOrdered.

    // 按照有限级别排序

   sortPostProcessors(priorityOrderedPostProcessors, beanFactory);

    // 注册beanProcessors

   registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

   // Next, register the BeanPostProcessors that implement Ordered.

   List orderedPostProcessors = new ArrayList<>();

   for (String ppName : orderedPostProcessorNames) {

      BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);

      orderedPostProcessors.add(pp);

      if (pp instanceof MergedBeanDefinitionPostProcessor) {

         internalPostProcessors.add(pp);

      }

   }

   sortPostProcessors(orderedPostProcessors, beanFactory);

   registerBeanPostProcessors(beanFactory, orderedPostProcessors);

   // Now, register all regular BeanPostProcessors.

   List nonOrderedPostProcessors = new ArrayList<>();

   for (String ppName : nonOrderedPostProcessorNames) {

      BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);

      nonOrderedPostProcessors.add(pp);

      if (pp instanceof MergedBeanDefinitionPostProcessor) {

         internalPostProcessors.add(pp);

      }

   }

   registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

   // Finally, re-register all internal BeanPostProcessors.

   sortPostProcessors(internalPostProcessors, beanFactory);

   registerBeanPostProcessors(beanFactory, internalPostProcessors);

   // Re-register post-processor for detecting inner beans as ApplicationListeners,

   // moving it to the end of the processor chain (for picking up proxies etc).

   beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));

}


你可能感兴趣的:(AnnotationConfigApplicationContext 启动流程)