Spring Boot源码阅读分析

文章目录

  • Spring Boot源码阅读分析
      • 1.SpringApplication实例创建和运行
        • 1.1 SpringApplication实例创建
          • new SpringApplication()
        • 1.2 SpringFactoriesLoader加载资源
        • 1.3 使用创建好的SpringApplication对象run()
        • 1.4 SpringApplicationRunListener注册
          • 概述:
        • 1.5 创建Context
        • 1.6 callRunners()
      • 2.refreshContext
        • 2.1 applicationContext.refresh()
        • 2.2 prepareRefresh()
        • 2.3 prepareBeanFactory(beanFactory)
        • 2.4 invokeBeanFactoryPostProcessors()
        • 2.5 finishBeanFactoryInitialization()
        • 2.6 finishRefresh()
      • 3.invokeBeanFactoryPostProcessors()
        • 3.1 processConfigBeanDefinitions()
        • 3.2 doProcessConfigurationClass()
        • 3.3 loadBeanDefinitionsForBeanMethod()
      • 4.preInstantiateSingletons()

Spring Boot源码阅读分析

注意:每个方法中的代码不一定是全代码,只是重点代码。

1.SpringApplication实例创建和运行

设计到的类为:ApplicationContextInitializer,ApplicationListener,SpringApplicationRunListener

1.1 SpringApplication实例创建

SpringApplication.run(Main.class, args)

new SpringApplication()
//Create a new SpringApplication instance. The application context will load beans from the specified //primary sources (see class-level documentation for details. The instance can be customized before calling //run(String...).
//部分代码
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources/*Main.class*/) {
     
   this.resourceLoader = resourceLoader;
   this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
   //设置webApplicationType的值
   this.webApplicationType = WebApplicationType.deduceFromClasspath();
   //获取bootstrappers对象,见1.2
   //getSpringFactoriesInstances()方法在实例化对象时,会对对象进行排序。
   this.bootstrappers = new ArrayList<>(getSpringFactoriesInstances(Bootstrapper.class));
    //加载所有的ApplicationContextInitializer.class,见1.2
   setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
   //加载所有的ApplicationListener.class,见1.2
   setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
   this.mainApplicationClass = deduceMainApplicationClass();//设置程序运行的主类
}

1.2 SpringFactoriesLoader加载资源

General purpose factory loading mechanism for internal use within the framework.
SpringFactoriesLoader loads and instantiates factories of a given type from “META-INF/spring.factories” files which may be present in multiple JAR files in the classpath.

上述Bootstrapper.class,ApplicationContextInitializer.class,ApplicationListener.class都是通过该类获取并实例化的。

包括后来的SpringApplicationRunListener

加载/META-INF/spring.factories中的类的全类名,保存到内部cache(ConcurrentReferenceHashMap)变量中:

  1. 首先加载用户代码类路径下的/META-INF/spring.factories中定义的类
  2. 其次org/springframework/boot/spring-boot/2.4.2/spring-boot-2.4.2.jar!/META-INF/spring.factories
  3. org/springframework/spring-beans/5.3.3/spring-beans-5.3.3.jar!/META-INF/spring.factories
  4. org/springframework/boot/spring-boot-autoconfigure/2.4.2/spring-boot-autoconfigure-2.4.2.jar!/META-INF/spring.factories

最终cache中的内容:cache中保存的只是全类名,这些类后续通过SpringFactoriesLoader.createSpringFactoriesInstances()方法反射实例化。

Spring Boot源码阅读分析_第1张图片

1.3 使用创建好的SpringApplication对象run()

run(String… args) :Run the Spring application, creating and refreshing a new 【ApplicationContext】.

#SpringApplication.run(String... args)部分代码
public ConfigurableApplicationContext run(String... args/*程序传入的参数*/) {
     
   DefaultBootstrapContext bootstrapContext = createBootstrapContext();//创建bootstrapContext
   ConfigurableApplicationContext context = null;
   configureHeadlessProperty();
   SpringApplicationRunListeners listeners = getRunListeners(args);//注册SpringApplicationRunListener1.4
   //调用listeners.start方法,此时SpringApplicationRunListener.starting()和					ApplicationRunListener.onApplicationEvent()方法都会被调用。
   listeners.starting(bootstrapContext, this.mainApplicationClass);
   try {
     
       //包装命令行参数
      ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
      //设置运行环境,此时SpringApplicationRunListener.environmentPrepared()和					ApplicationRunListener.onApplicationEvent()方法都会被调用
      ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
      configureIgnoreBeanInfo(environment);
      Banner printedBanner = printBanner(environment);//打印Springboot启动标记到控制台
      context = createApplicationContext();//创建相应的context,见1.5
      context.setApplicationStartup(this.applicationStartup);
       //准备,会调用SpringApplicationRunListener,ApplicationRunListener,和ApplicationContextInitializer相应的方法
      prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
      //关键,Bean的实例化,见2
      refreshContext(context);
      afterRefresh(context, applicationArguments);
      stopWatch.stop();
      if (this.logStartupInfo) {
     
         new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
      }
      listeners.started(context);
      //调用Runner方法,见1.6
      callRunners(context, applicationArguments);
   }
   catch (Throwable ex) {
     
      handleRunFailure(context, ex, listeners);
      throw new IllegalStateException(ex);
   }

   try {
     
      //调用系统所有listener的相应的方法,包括之前注册到容器的Applicationlistener。
      listeners.running(context);
   }
   catch (Throwable ex) {
     
      handleRunFailure(context, ex, null);
      throw new IllegalStateException(ex);
   }
    //返回该容器
   return context;
}

1.4 SpringApplicationRunListener注册

概述:
  • Listener for the SpringApplication run method.——SpringApplication运行方法的侦听器。
  • should declare a public construcstor that accepts a SpringApplication instance and a String[] of arguments.
  • SpringApplicationRunListener和SpringApplicationRunListeners使用了观察者模式,分别是观察者模式中的观察者和主题。

不过往主题中注册观察者是通过类 SpringFactoriesLoader;在SpringApplication实例化时,已经使用SpringFactoriesLoader将系统使用的所有SpringApplicationRunListener全类名从/META-INF/spring.factories注册到SpringFactoriesLoader.cache中。

private SpringApplicationRunListeners getRunListeners(String[] args) {
     
    ...
   //同1.1 Bootstrapper.class,ApplicationContextInitializer.class,ApplicationListener.class
   return new SpringApplicationRunListeners(logger,
         //获取所有的SpringApplicationRunListener.class对象,返回对象集合。
         getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args),
         this.applicationStartup);
}

1.5 创建Context

//根据webApplicationType实例化相应的Context对象,webApplicationType值见1.1
ApplicationContextFactory DEFAULT = (webApplicationType) -> {
     
   try {
     
      switch (webApplicationType) {
     
      case SERVLET:
         return new AnnotationConfigServletWebServerApplicationContext();
      case REACTIVE:
         return new AnnotationConfigReactiveWebServerApplicationContext();
      default:
         return new AnnotationConfigApplicationContext();
      }
   }
   catch (Exception ex) {
     
      throw new IllegalStateException("Unable create a default ApplicationContext instance, "
            + "you may need a custom ApplicationContextFactory", ex);
   }
};

1.6 callRunners()

private void callRunners(ApplicationContext context, ApplicationArguments args) {
     
   List<Object> runners = new ArrayList<>();
   runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
   runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
   AnnotationAwareOrderComparator.sort(runners);
   //对系统所有的runner调用其方法。
   for (Object runner : new LinkedHashSet<>(runners)) {
     
      if (runner instanceof ApplicationRunner) {
     
         callRunner((ApplicationRunner) runner, args);
      }
      if (runner instanceof CommandLineRunner) {
     
         callRunner((CommandLineRunner) runner, args);
      }
   }
}

2.refreshContext

进行与IOC容器相关的工作。涉及到的类为BeanFactoryPostProcessor,BeanPostProcessor,BeanDefinitionRegistryPostProcessor;和自定义的Bean。

2.1 applicationContext.refresh()

public void refresh() throws BeansException, IllegalStateException {
     
   synchronized (this.startupShutdownMonitor) {
     
   
      // Prepare this context for refreshing.见2.2
      prepareRefresh();

      // Tell the subclass to refresh the internal bean factory.
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

      // Prepare the bean factory for use in this context.见2.3
      prepareBeanFactory(beanFactory);

      try {
     
         // Allows post-processing of the bean factory in context subclasses.
          //空方法
         postProcessBeanFactory(beanFactory);
		
         // Invoke factory processors registered as beans in the context.
         //重点,注册BeanDefinition。
         //BeanFactoryPostProcessor即其子接口BeanDefinitionRegistryPostProcessor会在该方法中被实例化和调用其接口方法。见2.4
          //先实例化和调用BeanDefinitionRegistryPostProcessor得方法,其次是BeanFactoryPostProcessor。
         invokeBeanFactoryPostProcessors(beanFactory);

         // Register bean processors that intercept bean creation.
          //实例化所有得BeanPostProcessor。
         registerBeanPostProcessors(beanFactory);
         beanPostProcess.end();

         // Initialize message source for this context.
         initMessageSource();

         // Initialize event multicaster for this context.
         initApplicationEventMulticaster();

         // Initialize other special beans in specific context subclasses.
          //空方法,留个子类实现
         onRefresh();

         // Check for listener beans and register them.
          //注册Applicationlistener到applicationEventMulticaster属性中,如果此Applicationlistener没有初始化,则并不会初始化,只是注册一个名字。
         registerListeners();

         // Instantiate all remaining (non-lazy-init) singletons.
         //重点。只会实例化(1.非lazy-init,2.单实例)得Bean。-----------------------------------------
         //见2.5
         finishBeanFactoryInitialization(beanFactory);

         // Last step: publish corresponding event.
         //见2.6
         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();
         contextRefresh.end();
      }
   }
}

2.2 prepareRefresh()

// Initialize any placeholder property sources in the context environment.
//这个方法是空方法,留给子类去实现。
initPropertySources();

// Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
getEnvironment().validateRequiredProperties();

// Store pre-refresh ApplicationListeners...
if (this.earlyApplicationListeners == null) {
     
		this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
     
		// Reset local application listeners to pre-refresh state.
		this.applicationListeners.clear();
		this.applicationListeners.addAll(this.earlyApplicationListeners);
}

2.3 prepareBeanFactory(beanFactory)

//Configure the factory's standard context characteristics, such as the context's ClassLoader and post-processors.
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
     
   // Tell the internal bean factory to use the context's class loader etc.
   beanFactory.setBeanClassLoader(getClassLoader());
   if (!shouldIgnoreSpel) {
     
      beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
   }
   beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

   // Configure the bean factory with context callbacks.
   //注册一个系统BeanPostProcessor
   beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
   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.ignoreDependencyInterface(ApplicationStartup.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.
   beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

   // Detect a LoadTimeWeaver and prepare for weaving, if found.
   if (!IN_NATIVE_IMAGE && 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.
   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());
   }
   if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
     
      beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
   }
}

2.4 invokeBeanFactoryPostProcessors()

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
     
   //静态方法,见3
   PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
}

2.5 finishBeanFactoryInitialization()

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 bean post-processor
   // (such as a PropertyPlaceholderConfigurer bean) registered any before:
   // at this point, primarily for resolution in annotation attribute values.
   if (!beanFactory.hasEmbeddedValueResolver()) {
     
      beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
   }

   // 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.
    //将BeanDifination缓存起来
   beanFactory.freezeConfiguration();

   // Instantiate all remaining (non-lazy-init) singletons.
   //重点,真正执行初始化
   //见4
   beanFactory.preInstantiateSingletons();
}

2.6 finishRefresh()

protected void finishRefresh() {
     
   // Clear context-level resource caches (such as ASM metadata from scanning).
   clearResourceCaches();

   // Initialize lifecycle processor for this context.
   initLifecycleProcessor();

   // Propagate refresh to lifecycle processor first.
   getLifecycleProcessor().onRefresh();

   // Publish the final event.
   publishEvent(new ContextRefreshedEvent(this));

   // Participate in LiveBeansView MBean, if active.
   if (!IN_NATIVE_IMAGE) {
     
      LiveBeansView.registerApplicationContext(this);
   }
}

3.invokeBeanFactoryPostProcessors()

  1. 解析注解,注册所有的BeanDefinition。
  2. 实例化所有的BeanDefinitionRegistryPostProcessor,并调用其方法postProcessBeanDefinitionRegistry()。
  3. 实例化所有的BeanFactoryPostProcessor,并调用其postProcessBeanFactory()方法。

上述步骤有先后顺序。

public static void invokeBeanFactoryPostProcessors(
      ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
     
	//注册所有的BeanDefinition,最终调用processConfigBeanDefinitions。见3.1
      invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
      currentRegistryProcessors.clear();

      // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
      ...

      // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
      //将用户自定义的所有的BeanDefinitionRegistryPostProcessor实例化。
      boolean reiterate = true;
      while (reiterate) {
     
         reiterate = false;
         postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
         for (String ppName : postProcessorNames) {
     
            if (!processedBeans.contains(ppName)) {
     
               currentRegistryProcessors.add(
                   //通过getBean方法实例化BeanDefinitionRegistryPostProcessor。
                   beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
               processedBeans.add(ppName);
               reiterate = true;
            }
         }
         //对BeanDefinitionRegistryPostProcessor集合进行排序。
         sortPostProcessors(currentRegistryProcessors, beanFactory);
         registryProcessors.addAll(currentRegistryProcessors);
         //调用BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry()方法。
         invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
         currentRegistryProcessors.clear();
      }
   }


   // Do not initialize FactoryBeans here: We need to leave all regular beans
   // uninitialized to let the bean factory post-processors apply to them!
	//实例化所有的BeanFactoryPostProcessor,并调用其接口方法。
   String[] postProcessorNames =
         beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

   // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
   // Ordered, and the rest.
   List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
   List<String> orderedPostProcessorNames = new ArrayList<>();
   List<String> 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<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
   for (String postProcessorName : orderedPostProcessorNames) {
     
      orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
   }
   sortPostProcessors(orderedPostProcessors, beanFactory);
   invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

   // Finally, invoke all other BeanFactoryPostProcessors.
   List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
   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();
}

3.1 processConfigBeanDefinitions()

//Build and validate a configuration model based on the registry of Configuration classes.
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
     
   List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
   String[] candidateNames = registry.getBeanDefinitionNames();

   //找到Main.class的Bean定义
   for (String beanName : candidateNames) {
     
      BeanDefinition beanDef = registry.getBeanDefinition(beanName);
      if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
     
         if (logger.isDebugEnabled()) {
     
            logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
         }
      }
      else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
     
         configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
      }
   }

   // Return immediately if no @Configuration classes were found
   if (configCandidates.isEmpty()) {
     
      return;
   }

   // Sort by previously determined @Order value, if applicable
   configCandidates.sort((bd1, bd2) -> {
     
      int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
      int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
      return Integer.compare(i1, i2);
   });

   // Detect any custom bean name generation strategy supplied through the enclosing application context
   SingletonBeanRegistry sbr = null;
   if (registry instanceof SingletonBeanRegistry) {
     
      sbr = (SingletonBeanRegistry) registry;
      if (!this.localBeanNameGeneratorSet) {
     
         BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
               AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
         if (generator != null) {
     
            this.componentScanBeanNameGenerator = generator;
            this.importBeanNameGenerator = generator;
         }
      }
   }

   if (this.environment == null) {
     
      this.environment = new StandardEnvironment();
   }

   // Parse each @Configuration class
   //解析@Configuration注解的类
   ConfigurationClassParser parser = new ConfigurationClassParser(
         this.metadataReaderFactory, this.problemReporter, this.environment,
         this.resourceLoader, this.componentScanBeanNameGenerator, registry);

   Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
   Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
   do {
     
      StartupStep processConfig = this.applicationStartup.start("spring.context.config-classes.parse");
      //开始解析,此时candidates只包含从SpringApplication传入的主类(Main.class)的定义。
      //最终对candidates中的每一项调用doProcessConfigurationClass(),见3.2
      //只解析包装带有注解@Component的类。
      parser.parse(candidates);
  
      //根据上述获得的包中的类集合,扫描该集合,判断每一个类是否是@Configuration注解标记的类,是则为其@Bean注解方法返回的类,生成相应的ConfigurationClassBeanDefinition对象。
       //最终调用loadBeanDefinitionsForBeanMethod(),见3.3
      this.reader.loadBeanDefinitions(configClasses);
       
      alreadyParsed.addAll(configClasses);
      processConfig.tag("classCount", () -> String.valueOf(configClasses.size())).end();

      candidates.clear();
      if (registry.getBeanDefinitionCount() > candidateNames.length) {
     
         String[] newCandidateNames = registry.getBeanDefinitionNames();
         Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
         Set<String> alreadyParsedClasses = new HashSet<>();
         for (ConfigurationClass configurationClass : alreadyParsed) {
     
            alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
         }
         for (String candidateName : newCandidateNames) {
     
            if (!oldCandidateNames.contains(candidateName)) {
     
               BeanDefinition bd = registry.getBeanDefinition(candidateName);
               if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
                     !alreadyParsedClasses.contains(bd.getBeanClassName())) {
     
                  candidates.add(new BeanDefinitionHolder(bd, candidateName));
               }
            }
         }
         candidateNames = newCandidateNames;
      }
   }
   while (!candidates.isEmpty());

   // Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
   if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
     
      sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
   }

   if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
     
      // Clear cache in externally provided MetadataReaderFactory; this is a no-op
      // for a shared cache since it'll be cleared by the ApplicationContext.
      ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
   }
}

3.2 doProcessConfigurationClass()

protected final SourceClass doProcessConfigurationClass(
      ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
      throws IOException {
     

   if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
     
      // Recursively process any member (nested) classes first
      processMemberClasses(configClass, sourceClass, filter);
   }

   // Process any @PropertySource annotations
   for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
         sourceClass.getMetadata(), PropertySources.class,
         org.springframework.context.annotation.PropertySource.class)) {
     
      if (this.environment instanceof ConfigurableEnvironment) {
     
         processPropertySource(propertySource);
      }
      else {
     
         logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
               "]. Reason: Environment must implement ConfigurableEnvironment");
      }
   }

   // Process any @ComponentScan annotations--------------------------------------------------------
   Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
         sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
   if (!componentScans.isEmpty() &&
         !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
     
      for (AnnotationAttributes componentScan : componentScans) {
     
         // The config class is annotated with @ComponentScan -> perform the scan immediately
         Set<BeanDefinitionHolder> scannedBeanDefinitions =
             //按包和类名的字典序扫描包中的类,并为其生成一个ScannedGenericBeanDefinition对象。
             //此步只会扫描到包及子包中加了@Component注解的类。
               this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
         // Check the set of scanned definitions for any further config classes and parse recursively if needed
         for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
     
            BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
            if (bdCand == null) {
     
               bdCand = holder.getBeanDefinition();
            }
            if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
     
               parse(bdCand.getBeanClassName(), holder.getBeanName());
            }
         }
      }
   }

   // Process any @Import annotations
   processImports(configClass, sourceClass, getImports(sourceClass), filter, true);

   // Process any @ImportResource annotations
   AnnotationAttributes importResource =
         AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
   if (importResource != null) {
     
      String[] resources = importResource.getStringArray("locations");
      Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
      for (String resource : resources) {
     
         String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
         configClass.addImportedResource(resolvedResource, readerClass);
      }
   }

   // Process individual @Bean methods
   Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
   for (MethodMetadata methodMetadata : beanMethods) {
     
      configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
   }

   // Process default methods on interfaces
   processInterfaces(configClass, sourceClass);

   // Process superclass, if any
   if (sourceClass.getMetadata().hasSuperClass()) {
     
      String superclass = sourceClass.getMetadata().getSuperClassName();
      if (superclass != null && !superclass.startsWith("java") &&
            !this.knownSuperclasses.containsKey(superclass)) {
     
         this.knownSuperclasses.put(superclass, configClass);
         // Superclass found, return its annotation metadata and recurse
         return sourceClass.getSuperClass();
      }
   }

   // No superclass -> processing is complete
   return null;
}

3.3 loadBeanDefinitionsForBeanMethod()

private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) {
     
   ConfigurationClass configClass = beanMethod.getConfigurationClass();
   MethodMetadata metadata = beanMethod.getMetadata();
   String methodName = metadata.getMethodName();

   // Do we need to mark the bean as skipped by its condition?
   if (this.conditionEvaluator.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN)) {
     
      configClass.skippedBeanMethods.add(methodName);
      return;
   }
   if (configClass.skippedBeanMethods.contains(methodName)) {
     
      return;
   }

   AnnotationAttributes bean = AnnotationConfigUtils.attributesFor(metadata, Bean.class);
   Assert.state(bean != null, "No @Bean annotation attributes");

   // Consider name and any aliases
   List<String> names = new ArrayList<>(Arrays.asList(bean.getStringArray("name")));
   String beanName = (!names.isEmpty() ? names.remove(0) : methodName);

   // Register aliases even when overridden
   for (String alias : names) {
     
      this.registry.registerAlias(beanName, alias);
   }

   // Has this effectively been overridden before (e.g. via XML)?
   if (isOverriddenByExistingDefinition(beanMethod, beanName)) {
     
      if (beanName.equals(beanMethod.getConfigurationClass().getBeanName())) {
     
         throw new BeanDefinitionStoreException(beanMethod.getConfigurationClass().getResource().getDescription(),
               beanName, "Bean name derived from @Bean method '" + beanMethod.getMetadata().getMethodName() +
               "' clashes with bean name for containing configuration class; please make those names unique!");
      }
      return;
   }
	//生成ConfigurationClassBeanDefinition对象,代表该Bean定义。
   ConfigurationClassBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass, metadata, beanName);
   beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource()));

   if (metadata.isStatic()) {
     
      // static @Bean method
      if (configClass.getMetadata() instanceof StandardAnnotationMetadata) {
     
         beanDef.setBeanClass(((StandardAnnotationMetadata) configClass.getMetadata()).getIntrospectedClass());
      }
      else {
     
         beanDef.setBeanClassName(configClass.getMetadata().getClassName());
      }
      beanDef.setUniqueFactoryMethodName(methodName);
   }
   else {
     
      // instance @Bean method
      beanDef.setFactoryBeanName(configClass.getBeanName());
      beanDef.setUniqueFactoryMethodName(methodName);
   }

   if (metadata instanceof StandardMethodMetadata) {
     
      beanDef.setResolvedFactoryMethod(((StandardMethodMetadata) metadata).getIntrospectedMethod());
   }

   beanDef.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
   beanDef.setAttribute(org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.
         SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE);

   AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata);

   Autowire autowire = bean.getEnum("autowire");
   if (autowire.isAutowire()) {
     
      beanDef.setAutowireMode(autowire.value());
   }

   boolean autowireCandidate = bean.getBoolean("autowireCandidate");
   if (!autowireCandidate) {
     
      beanDef.setAutowireCandidate(false);
   }

   String initMethodName = bean.getString("initMethod");
   if (StringUtils.hasText(initMethodName)) {
     
      beanDef.setInitMethodName(initMethodName);
   }

   String destroyMethodName = bean.getString("destroyMethod");
   beanDef.setDestroyMethodName(destroyMethodName);

   // Consider scoping
   ScopedProxyMode proxyMode = ScopedProxyMode.NO;
   AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(metadata, Scope.class);
   if (attributes != null) {
     
      beanDef.setScope(attributes.getString("value"));
      proxyMode = attributes.getEnum("proxyMode");
      if (proxyMode == ScopedProxyMode.DEFAULT) {
     
         proxyMode = ScopedProxyMode.NO;
      }
   }

   // Replace the original bean definition with the target one, if necessary
   BeanDefinition beanDefToRegister = beanDef;
   if (proxyMode != ScopedProxyMode.NO) {
     
      BeanDefinitionHolder proxyDef = ScopedProxyCreator.createScopedProxy(
            new BeanDefinitionHolder(beanDef, beanName), this.registry,
            proxyMode == ScopedProxyMode.TARGET_CLASS);
      beanDefToRegister = new ConfigurationClassBeanDefinition(
            (RootBeanDefinition) proxyDef.getBeanDefinition(), configClass, metadata, beanName);
   }

   if (logger.isTraceEnabled()) {
     
      logger.trace(String.format("Registering bean definition for @Bean method %s.%s()",
            configClass.getMetadata().getClassName(), beanName));
   }
   this.registry.registerBeanDefinition(beanName, beanDefToRegister);
}

4.preInstantiateSingletons()

//初始化所有的非懒初始化的单例Bean
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);

   // Trigger initialization of all non-lazy singleton beans...
    //循环取出beanDefinitionName,调用getBean(beanName)实例化Bean。getBean见后。
   for (String beanName : beanNames) {
     
      RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
      if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
     
         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 {
     
            getBean(beanName);
         }
      }
   }

   // Trigger post-initialization callback for all applicable beans...
   //调用所有实现了接口SmartInitializingSingleton的afterSingletonsInstantiated()方法。
   for (String beanName : beanNames) {
     
      Object singletonInstance = getSingleton(beanName);
      if (singletonInstance instanceof SmartInitializingSingleton) {
     
         StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize")
               .tag("beanName", beanName);
         SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
         if (System.getSecurityManager() != null) {
     
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
     
               smartSingleton.afterSingletonsInstantiated();
               return null;
            }, getAccessControlContext());
         }
         else {
     
            smartSingleton.afterSingletonsInstantiated();
         }
         smartInitialize.end();
      }
   }
}
afterSingletonsInstantiated()方法。
   for (String beanName : beanNames) {
     
      Object singletonInstance = getSingleton(beanName);
      if (singletonInstance instanceof SmartInitializingSingleton) {
     
         StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize")
               .tag("beanName", beanName);
         SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
         if (System.getSecurityManager() != null) {
     
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
     
               smartSingleton.afterSingletonsInstantiated();
               return null;
            }, getAccessControlContext());
         }
         else {
     
            smartSingleton.afterSingletonsInstantiated();
         }
         smartInitialize.end();
      }
   }
}

你可能感兴趣的:(SpringBoot,spring,spring,boot,java)