• 一次搞懂SpringBoot核心原理:自动配置、事件驱动、Condition


    前言

    SpringBoot是Spring的包装,通过自动配置使得SpringBoot可以做到开箱即用,上手成本非常低,但是学习其实现原理的成本大大增加,需要先了解熟悉Spring原理。如果还不清楚Spring原理的,可以先查看博主之前的文章,本篇主要分析SpringBoot的启动、自动配置、Condition、事件驱动原理。

    启动原理

    SpringBoot启动非常简单,因其内置了Tomcat,所以只需要通过下面几种方式启动即可:

    1. @SpringBootApplication(scanBasePackages = {"cn.dark"})
    2. public class SpringbootDemo {
    3. public static void main(String[] args) {
    4. // 第一种
    5. SpringApplication.run(SpringbootDemo .class, args);
    6. // 第二种
    7. new SpringApplicationBuilder(SpringbootDemo .class)).run(args);
    8. // 第三种
    9. SpringApplication springApplication = new SpringApplication(SpringbootDemo.class);
    10. springApplication.run();
    11. }
    12. }

    可以看到第一种是最简单的,也是最常用的方式,需要注意类上面需要标注@SpringBootApplication注解,这是自动配置的核心实现,稍后分析,先来看看SpringBoot启动做了些什么?

    在往下之前,不妨先猜测一下,run方法中需要做什么?对比Spring源码,我们知道,Spring的启动都会创建一个ApplicationContext的应用上下文对象,并调用其refresh方法启动容器,SpringBoot只是Spring的一层壳,肯定也避免不了这样的操作。另一方面,以前通过Spring搭建的项目,都需要打成War包发布到Tomcat才行,而现在SpringBoot已经内置了Tomcat,只需要打成Jar包启动即可,所以在run方法中肯定也会创建对应的Tomcat对象并启动。以上只是我们的猜想,下面就来验证,进入run方法:

    1. public ConfigurableApplicationContext run(String... args) {
    2. // 统计时间用的工具类
    3. StopWatch stopWatch = new StopWatch();
    4. stopWatch.start();
    5. ConfigurableApplicationContext context = null;
    6. Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
    7. configureHeadlessProperty();
    8. // 获取实现了SpringApplicationRunListener接口的实现类,通过SPI机制加载
    9. // META-INF/spring.factories文件下的类
    10. SpringApplicationRunListeners listeners = getRunListeners(args);
    11. // 首先调用SpringApplicationRunListener的starting方法
    12. listeners.starting();
    13. try {
    14. ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
    15. // 处理配置数据
    16. ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
    17. configureIgnoreBeanInfo(environment);
    18. // 启动时打印banner
    19. Banner printedBanner = printBanner(environment);
    20. // 创建上下文对象
    21. context = createApplicationContext();
    22. // 获取SpringBootExceptionReporter接口的类,异常报告
    23. exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
    24. new Class[] { ConfigurableApplicationContext.class }, context);
    25. prepareContext(context, environment, listeners, applicationArguments, printedBanner);
    26. // 核心方法,启动spring容器
    27. refreshContext(context);
    28. afterRefresh(context, applicationArguments);
    29. // 统计结束
    30. stopWatch.stop();
    31. if (this.logStartupInfo) {
    32. new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
    33. }
    34. // 调用started
    35. listeners.started(context);
    36. // ApplicationRunner
    37. // CommandLineRunner
    38. // 获取这两个接口的实现类,并调用其run方法
    39. callRunners(context, applicationArguments);
    40. }
    41. catch (Throwable ex) {
    42. handleRunFailure(context, ex, exceptionReporters, listeners);
    43. throw new IllegalStateException(ex);
    44. }
    45. try {
    46. // 最后调用running方法
    47. listeners.running(context);
    48. }
    49. catch (Throwable ex) {
    50. handleRunFailure(context, ex, exceptionReporters, null);
    51. throw new IllegalStateException(ex);
    52. }
    53. return context;
    54. }

    SpringBoot的启动流程就是这个方法,先看getRunListeners方法,这个方法就是去拿到所有的
    SpringApplicationRunListener实现类,这些类是用于SpringBoot事件发布的,关于事件驱动稍后分析,这里主要看这个方法的实现原理:

    1. private SpringApplicationRunListeners getRunListeners(String[] args) {
    2. Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
    3. return new SpringApplicationRunListeners(logger,
    4. getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args));
    5. }
    6. private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
    7. ClassLoader classLoader = getClassLoader();
    8. // Use names and ensure unique to protect against duplicates
    9. Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
    10. // 加载上来后反射实例化
    11. List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
    12. AnnotationAwareOrderComparator.sort(instances);
    13. return instances;
    14. }
    15. public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
    16. String factoryTypeName = factoryType.getName();
    17. return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
    18. }
    19. public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
    20. private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
    21. MultiValueMap<String, String> result = cache.get(classLoader);
    22. if (result != null) {
    23. return result;
    24. }
    25. try {
    26. Enumeration<URL> urls = (classLoader != null ?
    27. classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
    28. ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
    29. result = new LinkedMultiValueMap<>();
    30. while (urls.hasMoreElements()) {
    31. URL url = urls.nextElement();
    32. UrlResource resource = new UrlResource(url);
    33. Properties properties = PropertiesLoaderUtils.loadProperties(resource);
    34. for (Map.Entry<?, ?> entry : properties.entrySet()) {
    35. String factoryTypeName = ((String) entry.getKey()).trim();
    36. for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
    37. result.add(factoryTypeName, factoryImplementationName.trim());
    38. }
    39. }
    40. }
    41. cache.put(classLoader, result);
    42. return result;
    43. }
    44. }

    一步步追踪下去可以看到最终就是通过SPI机制根据接口类型从META-INF/spring.factories文件中加载对应的实现类并实例化,SpringBoot的自动配置也是这样实现的。为什么要这样实现呢?通过注解扫描不可以么?当然不行,这些类都在第三方jar包中,注解扫描实现是很麻烦的,当然你也可以通过@Import注解导入,但是这种方式不适合扩展类特别多的情况,所以这里采用SPI的优点就显而易见了。

    回到run方法中,可以看到调用了createApplicationContext方法,见名知意,这个就是去创建应用上下文对象:

    1. public static final String DEFAULT_SERVLET_WEB_CONTEXT_CLASS = "org.springframework.boot."
    2. + "web.servlet.context.AnnotationConfigServletWebServerApplicationContext";
    3. protected ConfigurableApplicationContext createApplicationContext() {
    4. Class<?> contextClass = this.applicationContextClass;
    5. if (contextClass == null) {
    6. try {
    7. switch (this.webApplicationType) {
    8. case SERVLET:
    9. contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
    10. break;
    11. case REACTIVE:
    12. contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
    13. break;
    14. default:
    15. contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
    16. }
    17. }
    18. catch (ClassNotFoundException ex) {
    19. throw new IllegalStateException(
    20. "Unable create a default ApplicationContext, please specify an ApplicationContextClass", ex);
    21. }
    22. }
    23. return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
    24. }

    注意这里通过反射实例化了一个新的没见过的上下文对象
    AnnotationConfigServletWebServerApplicationContext,这个是SpringBoot扩展的,看看其构造方法:

    1. public AnnotationConfigServletWebServerApplicationContext() {
    2. this.reader = new AnnotatedBeanDefinitionReader(this);
    3. this.scanner = new ClassPathBeanDefinitionScanner(this);
    4. }

    如果你有看过Spring注解驱动的实现原理,这两个对象肯定不会陌生,一个实支持注解解析的,另外一个是扫描包用的。
    上下文创建好了,下一步自然就是调用refresh方法启动容器:

    1. private void refreshContext(ConfigurableApplicationContext context) {
    2. refresh(context);
    3. if (this.registerShutdownHook) {
    4. try {
    5. context.registerShutdownHook();
    6. }
    7. catch (AccessControlException ex) {
    8. // Not allowed in some environments.
    9. }
    10. }
    11. }
    12. protected void refresh(ApplicationContext applicationContext) {
    13. Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
    14. ((AbstractApplicationContext) applicationContext).refresh();
    15. }

    这里首先会调用到其父类中
    ServletWebServerApplicationContext

    1. public final void refresh() throws BeansException, IllegalStateException {
    2. try {
    3. super.refresh();
    4. }
    5. catch (RuntimeException ex) {
    6. stopAndReleaseWebServer();
    7. throw ex;
    8. }
    9. }

    可以看到是直接委托给了父类:

    1. public void refresh() throws BeansException, IllegalStateException {
    2. synchronized (this.startupShutdownMonitor) {
    3. // Prepare this context for refreshing.
    4. prepareRefresh();
    5. // Tell the subclass to refresh the internal bean factory.
    6. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
    7. // Prepare the bean factory for use in this context.
    8. prepareBeanFactory(beanFactory);
    9. try {
    10. // Allows post-processing of the bean factory in context subclasses.
    11. postProcessBeanFactory(beanFactory);
    12. // Invoke factory processors registered as beans in the context.
    13. invokeBeanFactoryPostProcessors(beanFactory);
    14. // Register bean processors that intercept bean creation.
    15. registerBeanPostProcessors(beanFactory);
    16. // Initialize message source for this context.
    17. initMessageSource();
    18. // Initialize event multicaster for this context.
    19. initApplicationEventMulticaster();
    20. // Initialize other special beans in specific context subclasses.
    21. onRefresh();
    22. // Check for listener beans and register them.
    23. registerListeners();
    24. // Instantiate all remaining (non-lazy-init) singletons.
    25. finishBeanFactoryInitialization(beanFactory);
    26. // Last step: publish corresponding event.
    27. finishRefresh();
    28. }
    29. catch (BeansException ex) {
    30. if (logger.isWarnEnabled()) {
    31. logger.warn("Exception encountered during context initialization - " +
    32. "cancelling refresh attempt: " + ex);
    33. }
    34. // Destroy already created singletons to avoid dangling resources.
    35. destroyBeans();
    36. // Reset 'active' flag.
    37. cancelRefresh(ex);
    38. // Propagate exception to caller.
    39. throw ex;
    40. }
    41. finally {
    42. // Reset common introspection caches in Spring's core, since we
    43. // might not ever need metadata for singleton beans anymore...
    44. resetCommonCaches();
    45. }
    46. }
    47. }

    这个方法不会陌生吧,之前已经分析过了,这里不再赘述,至此SpringBoot的容器就启动了,但是Tomcat启动是在哪里呢?run方法中也没有看到。实际上Tomcat的启动也是在refresh流程中,这个方法其中一步是调用了onRefresh方法,在Spring中这是一个没有实现的模板方法,而SpringBoot就通过这个方法完成了Tomcat的启动:

    1. protected void onRefresh() {
    2. super.onRefresh();
    3. try {
    4. createWebServer();
    5. }
    6. catch (Throwable ex) {
    7. throw new ApplicationContextException("Unable to start web server", ex);
    8. }
    9. }
    10. private void createWebServer() {
    11. WebServer webServer = this.webServer;
    12. ServletContext servletContext = getServletContext();
    13. if (webServer == null && servletContext == null) {
    14. ServletWebServerFactory factory = getWebServerFactory();
    15. // 主要看这个方法
    16. this.webServer = factory.getWebServer(getSelfInitializer());
    17. }
    18. else if (servletContext != null) {
    19. try {
    20. getSelfInitializer().onStartup(servletContext);
    21. }
    22. catch (ServletException ex) {
    23. throw new ApplicationContextException("Cannot initialize servlet context", ex);
    24. }
    25. }
    26. initPropertySources();
    27. }

    这里首先拿到
    TomcatServletWebServerFactory对象,通过该对象再去创建和启动Tomcat:

    1. public WebServer getWebServer(ServletContextInitializer... initializers) {
    2. if (this.disableMBeanRegistry) {
    3. Registry.disableRegistry();
    4. }
    5. Tomcat tomcat = new Tomcat();
    6. File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
    7. tomcat.setBaseDir(baseDir.getAbsolutePath());
    8. Connector connector = new Connector(this.protocol);
    9. connector.setThrowOnFailure(true);
    10. tomcat.getService().addConnector(connector);
    11. customizeConnector(connector);
    12. tomcat.setConnector(connector);
    13. tomcat.getHost().setAutoDeploy(false);
    14. configureEngine(tomcat.getEngine());
    15. for (Connector additionalConnector : this.additionalTomcatConnectors) {
    16. tomcat.getService().addConnector(additionalConnector);
    17. }
    18. prepareContext(tomcat.getHost(), initializers);
    19. return getTomcatWebServer(tomcat);
    20. }

    上面的每一步都可以对比Tomcat的配置文件,需要注意默认只支持了http协议:

    1. Connector connector = new Connector(this.protocol);
    2. private String protocol = DEFAULT_PROTOCOL;
    3. public static final String DEFAULT_PROTOCOL = "org.apache.coyote.http11.Http11NioProtocol";

    如果想要扩展的话则可以对
    additionalTomcatConnectors属性设置值,需要注意这个属性没有对应的setter方法,只有addAdditionalTomcatConnectors方法,也就是说我们只能通过实现BeanFactoryPostProcessor接口的postProcessBeanFactory方法,而不能通过BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法,因为前者可以通过传入的BeanFactory对象提前获取到TomcatServletWebServerFactory对象调用addAdditionalTomcatConnectors即可;而后者只能拿到BeanDefinition对象,该对象只能通过setter方法设置值。

    事件驱动

    Spring原本就提供了事件机制,而在SpringBoot中又对其进行扩展,通过发布订阅事件在容器的整个生命周期的不同阶段进行不同的操作。我们先来看看SpringBoot启动关闭的过程中默认会发布哪些事件,使用下面的代码即可:

    1. @SpringBootApplication
    2. public class SpringEventDemo {
    3. public static void main(String[] args) {
    4. new SpringApplicationBuilder(SpringEventDemo.class)
    5. .listeners(event -> {
    6. System.err.println("接收到事件:" + event.getClass().getSimpleName());
    7. })
    8. .run()
    9. .close();
    10. }
    11. }

    这段代码会在控制台打印所有的事件名称,按照顺序如下:

    • ApplicationStartingEvent:容器启动
    • ApplicationEnvironmentPreparedEvent:环境准备好
    • ApplicationContextInitializedEvent:上下文初始化完成
    • ApplicationPreparedEvent:上下文准备好
    • ContextRefreshedEvent:上下文刷新完
    • ServletWebServerInitializedEvent:webServer初始化完成
    • ApplicationStartedEvent:容器启动完成
    • ApplicationReadyEvent:容器就绪
    • ContextClosedEvent:容器关闭

    以上是正常启动关闭,如果发生异常还有发布ApplicationFailedEvent事件。事件的发布遍布在整个容器的启动关闭周期中,事件发布对象刚刚我们也看到了是通过SPI加载的
    SpringApplicationRunListener实现类EventPublishingRunListener,同样事件监听器也是在spring.factories文件中配置的,默认实现了以下监听器:

    1. org.springframework.context.ApplicationListener=\
    2. org.springframework.boot.ClearCachesApplicationListener,\
    3. org.springframework.boot.builder.ParentContextCloserApplicationListener,\
    4. org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor,\
    5. org.springframework.boot.context.FileEncodingApplicationListener,\
    6. org.springframework.boot.context.config.AnsiOutputApplicationListener,\
    7. org.springframework.boot.context.config.ConfigFileApplicationListener,\
    8. org.springframework.boot.context.config.DelegatingApplicationListener,\
    9. org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\
    10. org.springframework.boot.context.logging.LoggingApplicationListener,\
    11. org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener

    可以看到有用于文件编码的(
    FileEncodingApplicationListener),有加载日志框架的(LoggingApplicationListener),还有加载配置的(ConfigFileApplicationListener)等等一系列监听器,SpringBoot也就是通过这系列监听器将必要的配置和组件加载到容器中来,这里不再详细分析,感兴趣的读者可以通过其实现的onApplicationEvent方法看到每个监听器究竟是监听的哪一个事件,当然事件发布和监听我们自己也是可以扩展的。

    自动配置原理

    SpringBoot最核心的还是自动配置,为什么它能做到开箱即用,不再需要我们手动使用@EnableXXX等注解来开启?这一切的答案就在@SpringBootApplication注解中:

    1. @Target(ElementType.TYPE)
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Documented
    4. @Inherited
    5. @SpringBootConfiguration
    6. @EnableAutoConfiguration
    7. @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
    8. @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
    9. public @interface SpringBootApplication {}

    这里重要的注解有三个:@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan。@ComponentScan就不用再说了,@SpringBootConfiguration等同于@Configuration,而@EnableAutoConfiguration就是开启自动配置:

    1. @AutoConfigurationPackage
    2. @Import(AutoConfigurationImportSelector.class)
    3. public @interface EnableAutoConfiguration {
    4. }
    5. @Import(AutoConfigurationPackages.Registrar.class)
    6. public @interface AutoConfigurationPackage {
    7. }

    @AutoConfigurationPackage注解的作用就是将该注解所标记类所在的包作为自动配置的包,简单看看就行,主要看
    AutoConfigurationImportSelector,这个就是实现自动配置的核心类,注意这个类是实现的DeferredImportSelector接口。

    在这个类中有一个selectImports方法。这个方法在我之前的文章这一次搞懂Spring事务注解的解析也有分析过,只是实现类不同,它同样会被
    ConfigurationClassPostProcessor类调用,先来看这个方法做了些什么:

    1. public String[] selectImports(AnnotationMetadata annotationMetadata) {
    2. if (!isEnabled(annotationMetadata)) {
    3. return NO_IMPORTS;
    4. }
    5. AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
    6. .loadMetadata(this.beanClassLoader);
    7. // 获取所有的自动配置类
    8. AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(autoConfigurationMetadata,
    9. annotationMetadata);
    10. return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
    11. }
    12. protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata,
    13. AnnotationMetadata annotationMetadata) {
    14. if (!isEnabled(annotationMetadata)) {
    15. return EMPTY_ENTRY;
    16. }
    17. AnnotationAttributes attributes = getAttributes(annotationMetadata);
    18. // SPI获取EnableAutoConfiguration为key的所有实现类
    19. List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
    20. configurations = removeDuplicates(configurations);
    21. Set<String> exclusions = getExclusions(annotationMetadata, attributes);
    22. checkExcludedClasses(configurations, exclusions);
    23. configurations.removeAll(exclusions);
    24. // 把某些自动配置类过滤掉
    25. configurations = filter(configurations, autoConfigurationMetadata);
    26. fireAutoConfigurationImportEvents(configurations, exclusions);
    27. // 包装成自动配置实体类
    28. return new AutoConfigurationEntry(configurations, exclusions);
    29. }
    30. protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
    31. // SPI获取EnableAutoConfiguration为key的所有实现类
    32. List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
    33. getBeanClassLoader());
    34. Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
    35. + "are using a custom packaging, make sure that file is correct.");
    36. return configurations;
    37. }

    追踪源码最终可以看到也是从META-INF/spring.factories文件中拿到所有EnableAutoConfiguration对应的值(在spring-boot-autoconfigure中)并通过反射实例化,过滤后包装成AutoConfigurationEntry对象返回。

    看到这里你应该会觉得自动配置的实现就是通过这个selectImports方法,但实际上这个方法通常并不会被调用到,而是会调用该类的内部类AutoConfigurationGroup的process和selectImports方法,前者同样是通过getAutoConfigurationEntry拿到所有的自动配置类,而后者这是过滤排序并包装后返回。

    下面就来分析
    ConfigurationClassPostProcessor是怎么调用到这里的,直接进入processConfigBeanDefinitions方法:

    1. public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
    2. List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
    3. String[] candidateNames = registry.getBeanDefinitionNames();
    4. for (String beanName : candidateNames) {
    5. BeanDefinition beanDef = registry.getBeanDefinition(beanName);
    6. if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
    7. if (logger.isDebugEnabled()) {
    8. logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
    9. }
    10. }
    11. else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
    12. configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
    13. }
    14. }
    15. // Return immediately if no @Configuration classes were found
    16. if (configCandidates.isEmpty()) {
    17. return;
    18. }
    19. // Sort by previously determined @Order value, if applicable
    20. configCandidates.sort((bd1, bd2) -> {
    21. int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
    22. int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
    23. return Integer.compare(i1, i2);
    24. });
    25. // Detect any custom bean name generation strategy supplied through the enclosing application context
    26. SingletonBeanRegistry sbr = null;
    27. if (registry instanceof SingletonBeanRegistry) {
    28. sbr = (SingletonBeanRegistry) registry;
    29. if (!this.localBeanNameGeneratorSet) {
    30. BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
    31. AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
    32. if (generator != null) {
    33. this.componentScanBeanNameGenerator = generator;
    34. this.importBeanNameGenerator = generator;
    35. }
    36. }
    37. }
    38. if (this.environment == null) {
    39. this.environment = new StandardEnvironment();
    40. }
    41. // Parse each @Configuration class
    42. ConfigurationClassParser parser = new ConfigurationClassParser(
    43. this.metadataReaderFactory, this.problemReporter, this.environment,
    44. this.resourceLoader, this.componentScanBeanNameGenerator, registry);
    45. Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
    46. Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
    47. do {
    48. parser.parse(candidates);
    49. parser.validate();
    50. Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
    51. configClasses.removeAll(alreadyParsed);
    52. // Read the model and create bean definitions based on its content
    53. if (this.reader == null) {
    54. this.reader = new ConfigurationClassBeanDefinitionReader(
    55. registry, this.sourceExtractor, this.resourceLoader, this.environment,
    56. this.importBeanNameGenerator, parser.getImportRegistry());
    57. }
    58. this.reader.loadBeanDefinitions(configClasses);
    59. alreadyParsed.addAll(configClasses);
    60. // 省略。。。。
    61. }

    前面一大段主要是拿到合格的Configuration配置类,主要逻辑是在
    ConfigurationClassParser.parse方法中,该方法完成了对@Component、@Bean、@Import、@ComponentScans等注解的解析,这里主要看对@Import的解析,其它的读者可自行分析。一步步追踪,最终会进入到processConfigurationClass方法:

    1. protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
    2. if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
    3. return;
    4. }
    5. ConfigurationClass existingClass = this.configurationClasses.get(configClass);
    6. if (existingClass != null) {
    7. if (configClass.isImported()) {
    8. if (existingClass.isImported()) {
    9. existingClass.mergeImportedBy(configClass);
    10. }
    11. // Otherwise ignore new imported config class; existing non-imported class overrides it.
    12. return;
    13. }
    14. else {
    15. // Explicit bean definition found, probably replacing an import.
    16. // Let's remove the old one and go with the new one.
    17. this.configurationClasses.remove(configClass);
    18. this.knownSuperclasses.values().removeIf(configClass::equals);
    19. }
    20. }
    21. // Recursively process the configuration class and its superclass hierarchy.
    22. SourceClass sourceClass = asSourceClass(configClass);
    23. do {
    24. sourceClass = doProcessConfigurationClass(configClass, sourceClass);
    25. }
    26. while (sourceClass != null);
    27. this.configurationClasses.put(configClass, configClass);
    28. }

    这里需要注意
    this.conditionEvaluator.shouldSkip方法的调用,这个方法就是进行Bean加载过滤的,即根据@Condition注解的匹配值判断是否加载该Bean,具体实现稍后分析,继续跟踪主流程
    doProcessConfigurationClass

    1. protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
    2. throws IOException {
    3. 省略....
    4. // Process any @Import annotations
    5. processImports(configClass, sourceClass, getImports(sourceClass), true);
    6. 省略....
    7. return null;
    8. }

    这里就是完成对一系列注解的支撑,我省略掉了,主要看processImports方法,这个方法就是处理@Import注解的:

    1. private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
    2. Collection<SourceClass> importCandidates, boolean checkForCircularImports) {
    3. if (importCandidates.isEmpty()) {
    4. return;
    5. }
    6. if (checkForCircularImports && isChainedImportOnStack(configClass)) {
    7. this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
    8. }
    9. else {
    10. this.importStack.push(configClass);
    11. try {
    12. for (SourceClass candidate : importCandidates) {
    13. if (candidate.isAssignable(ImportSelector.class)) {
    14. // Candidate class is an ImportSelector -> delegate to it to determine imports
    15. Class<?> candidateClass = candidate.loadClass();
    16. ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class,
    17. this.environment, this.resourceLoader, this.registry);
    18. if (selector instanceof DeferredImportSelector) {
    19. this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
    20. }
    21. else {
    22. String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
    23. Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames);
    24. processImports(configClass, currentSourceClass, importSourceClasses, false);
    25. }
    26. }
    27. else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
    28. Class<?> candidateClass = candidate.loadClass();
    29. ImportBeanDefinitionRegistrar registrar =
    30. ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
    31. this.environment, this.resourceLoader, this.registry);
    32. configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
    33. }
    34. else {
    35. this.importStack.registerImport(
    36. currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
    37. processConfigurationClass(candidate.asConfigClass(configClass));
    38. }
    39. }
    40. }
    41. }
    42. }

    刚刚我提醒过
    AutoConfigurationImportSelector是实现DeferredImportSelector接口的,如果不是该接口的实现类则是直接调用selectImports方法,反之则是调用DeferredImportSelectorHandler.handle方法:

    1. private List deferredImportSelectors = new ArrayList<>();
    2. public void handle(ConfigurationClass configClass, DeferredImportSelector importSelector) {
    3. DeferredImportSelectorHolder holder = new DeferredImportSelectorHolder(
    4. configClass, importSelector);
    5. if (this.deferredImportSelectors == null) {
    6. DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler();
    7. handler.register(holder);
    8. handler.processGroupImports();
    9. }
    10. else {
    11. this.deferredImportSelectors.add(holder);
    12. }
    13. }

    首先创建了一个
    DeferredImportSelectorHolder对象,如果是第一次执行则是添加到deferredImportSelectors属性中,等到
    ConfigurationClassParser.parse的最后调用process方法:

    1. public void parse(Set configCandidates) {
    2. 省略.....
    3. this.deferredImportSelectorHandler.process();
    4. }
    5. public void process() {
    6. List<DeferredImportSelectorHolder> deferredImports = this.deferredImportSelectors;
    7. this.deferredImportSelectors = null;
    8. try {
    9. if (deferredImports != null) {
    10. DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler();
    11. deferredImports.sort(DEFERRED_IMPORT_COMPARATOR);
    12. deferredImports.forEach(handler::register);
    13. handler.processGroupImports();
    14. }
    15. }
    16. finally {
    17. this.deferredImportSelectors = new ArrayList<>();
    18. }
    19. }

    反之则是直接执行,首先通过register拿到AutoConfigurationGroup对象:

    1. public void register(DeferredImportSelectorHolder deferredImport) {
    2. Class<? extends Group> group = deferredImport.getImportSelector()
    3. .getImportGroup();
    4. DeferredImportSelectorGrouping grouping = this.groupings.computeIfAbsent(
    5. (group != null ? group : deferredImport),
    6. key -> new DeferredImportSelectorGrouping(createGroup(group)));
    7. grouping.add(deferredImport);
    8. this.configurationClasses.put(deferredImport.getConfigurationClass().getMetadata(),
    9. deferredImport.getConfigurationClass());
    10. }
    11. public Class<? extends Group> getImportGroup() {
    12. return AutoConfigurationGroup.class;
    13. }

    然后在processGroupImports方法中进行真正的处理:

    1. public void processGroupImports() {
    2. for (DeferredImportSelectorGrouping grouping : this.groupings.values()) {
    3. grouping.getImports().forEach(entry -> {
    4. ConfigurationClass configurationClass = this.configurationClasses.get(
    5. entry.getMetadata());
    6. try {
    7. processImports(configurationClass, asSourceClass(configurationClass),
    8. asSourceClasses(entry.getImportClassName()), false);
    9. }
    10. catch (BeanDefinitionStoreException ex) {
    11. throw ex;
    12. }
    13. catch (Throwable ex) {
    14. throw new BeanDefinitionStoreException(
    15. "Failed to process import candidates for configuration class [" +
    16. configurationClass.getMetadata().getClassName() + "]", ex);
    17. }
    18. });
    19. }
    20. }
    21. public Iterable getImports() {
    22. for (DeferredImportSelectorHolder deferredImport : this.deferredImports) {
    23. this.group.process(deferredImport.getConfigurationClass().getMetadata(),
    24. deferredImport.getImportSelector());
    25. }
    26. return this.group.selectImports();
    27. }

     在getImports方法中就完成了对process和selectImports方法的调用,拿到自动配置类后再递归调用调用processImports方法完成对自动配置类的加载。至此,自动配置的加载过程就分析完了,下面是时序图:

    Condition注解原理

    在自动配置类中有很多Condition相关的注解,以AOP为例:

    1. Configuration(proxyBeanMethods = false)
    2. @ConditionalOnProperty(prefix = "spring.aop", name = "auto", havingValue = "true", matchIfMissing = true)
    3. public class AopAutoConfiguration {
    4. @Configuration(proxyBeanMethods = false)
    5. @ConditionalOnClass(Advice.class)
    6. static class AspectJAutoProxyingConfiguration {
    7. @Configuration(proxyBeanMethods = false)
    8. @EnableAspectJAutoProxy(proxyTargetClass = false)
    9. @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "false",
    10. matchIfMissing = false)
    11. static class JdkDynamicAutoProxyConfiguration {
    12. }
    13. @Configuration(proxyBeanMethods = false)
    14. @EnableAspectJAutoProxy(proxyTargetClass = true)
    15. @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true",
    16. matchIfMissing = true)
    17. static class CglibAutoProxyConfiguration {
    18. }
    19. }
    20. @Configuration(proxyBeanMethods = false)
    21. @ConditionalOnMissingClass("org.aspectj.weaver.Advice")
    22. @ConditionalOnProperty(prefix = "spring.aop", name = "proxy-target-class", havingValue = "true",
    23. matchIfMissing = true)
    24. static class ClassProxyingConfiguration {
    25. ClassProxyingConfiguration(BeanFactory beanFactory) {
    26. if (beanFactory instanceof BeanDefinitionRegistry) {
    27. BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
    28. AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
    29. AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry);
    30. }
    31. }
    32. }
    33. }

    这里就能看到@ConditionalOnProperty、@ConditionalOnClass、@ConditionalOnMissingClass,另外还有@ConditionalOnBean、@ConditionalOnMissingBean等等很多条件匹配注解。这些注解表示条件匹配才会加载该Bean,以@ConditionalOnProperty为例,表明配置文件中符合条件才会加载对应的Bean,prefix表示在配置文件中的前缀,name表示配置的名称,havingValue表示配置为该值时才匹配,matchIfMissing则是表示没有该配置是否默认加载对应的Bean。其它注解可类比理解记忆,下面主要来分析该注解的实现原理。

    这里注解点进去看会发现每个注解上都标注了@Conditional注解,并且value值都对应一个类,比如OnBeanCondition,而这些类都实现了Condition接口,看看其继承体系:

    ​上面只展示了几个实现类,但实际上Condition的实现类是非常多的,我们还可以自己实现该接口来扩展@Condition注解。

    Condition接口中有一个matches方法,这个方法返回true则表示匹配。该方法在ConfigurationClassParser中多处都有调用,也就是刚刚我提醒过的shouldSkip方法,具体实现是在ConditionEvaluator类中:

    1. public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) {
    2. if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
    3. return false;
    4. }
    5. if (phase == null) {
    6. if (metadata instanceof AnnotationMetadata &&
    7. ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) {
    8. return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
    9. }
    10. return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
    11. }
    12. List<Condition> conditions = new ArrayList<>();
    13. for (String[] conditionClasses : getConditionClasses(metadata)) {
    14. for (String conditionClass : conditionClasses) {
    15. Condition condition = getCondition(conditionClass, this.context.getClassLoader());
    16. conditions.add(condition);
    17. }
    18. }
    19. AnnotationAwareOrderComparator.sort(conditions);
    20. for (Condition condition : conditions) {
    21. ConfigurationPhase requiredPhase = null;
    22. if (condition instanceof ConfigurationCondition) {
    23. requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
    24. }
    25. if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) {
    26. return true;
    27. }
    28. }
    29. return false;
    30. }

    再来看看matches的实现,但OnBeanCondition类中没有实现该方法,而是在其父类SpringBootCondition中:

    1. public final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    2. String classOrMethodName = getClassOrMethodName(metadata);
    3. try {
    4. ConditionOutcome outcome = getMatchOutcome(context, metadata);
    5. logOutcome(classOrMethodName, outcome);
    6. recordEvaluation(context, classOrMethodName, outcome);
    7. return outcome.isMatch();
    8. }

    getMatchOutcome方法也是一个模板方法,具体的匹配逻辑就在这个方法中实现,该方法返回的ConditionOutcome对象就包含了是否匹配日志消息两个字段。进入到OnBeanCondition类中:

    1. public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
    2. ConditionMessage matchMessage = ConditionMessage.empty();
    3. MergedAnnotations annotations = metadata.getAnnotations();
    4. if (annotations.isPresent(ConditionalOnBean.class)) {
    5. Spec<ConditionalOnBean> spec = new Spec<>(context, metadata, annotations, ConditionalOnBean.class);
    6. MatchResult matchResult = getMatchingBeans(context, spec);
    7. if (!matchResult.isAllMatched()) {
    8. String reason = createOnBeanNoMatchReason(matchResult);
    9. return ConditionOutcome.noMatch(spec.message().because(reason));
    10. }
    11. matchMessage = spec.message(matchMessage).found("bean", "beans").items(Style.QUOTE,
    12. matchResult.getNamesOfAllMatches());
    13. }
    14. if (metadata.isAnnotated(ConditionalOnSingleCandidate.class.getName())) {
    15. Spec<ConditionalOnSingleCandidate> spec = new SingleCandidateSpec(context, metadata, annotations);
    16. MatchResult matchResult = getMatchingBeans(context, spec);
    17. if (!matchResult.isAllMatched()) {
    18. return ConditionOutcome.noMatch(spec.message().didNotFind("any beans").atAll());
    19. }
    20. else if (!hasSingleAutowireCandidate(context.getBeanFactory(), matchResult.getNamesOfAllMatches(),
    21. spec.getStrategy() == SearchStrategy.ALL)) {
    22. return ConditionOutcome.noMatch(spec.message().didNotFind("a primary bean from beans")
    23. .items(Style.QUOTE, matchResult.getNamesOfAllMatches()));
    24. }
    25. matchMessage = spec.message(matchMessage).found("a primary bean from beans").items(Style.QUOTE,
    26. matchResult.getNamesOfAllMatches());
    27. }
    28. if (metadata.isAnnotated(ConditionalOnMissingBean.class.getName())) {
    29. Spec<ConditionalOnMissingBean> spec = new Spec<>(context, metadata, annotations,
    30. ConditionalOnMissingBean.class);
    31. MatchResult matchResult = getMatchingBeans(context, spec);
    32. if (matchResult.isAnyMatched()) {
    33. String reason = createOnMissingBeanNoMatchReason(matchResult);
    34. return ConditionOutcome.noMatch(spec.message().because(reason));
    35. }
    36. matchMessage = spec.message(matchMessage).didNotFind("any beans").atAll();
    37. }
    38. return ConditionOutcome.match(matchMessage);
    39. }

    可以看到该类支持了@ConditionalOnBean、@
    ConditionalOnSingleCandidate、@ConditionalOnMissingBean注解,主要的匹配逻辑在getMatchingBeans方法中:

    1. protected final MatchResult getMatchingBeans(ConditionContext context, Spec<?> spec) {
    2. ClassLoader classLoader = context.getClassLoader();
    3. ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
    4. boolean considerHierarchy = spec.getStrategy() != SearchStrategy.CURRENT;
    5. Set<Class<?>> parameterizedContainers = spec.getParameterizedContainers();
    6. if (spec.getStrategy() == SearchStrategy.ANCESTORS) {
    7. BeanFactory parent = beanFactory.getParentBeanFactory();
    8. Assert.isInstanceOf(ConfigurableListableBeanFactory.class, parent,
    9. "Unable to use SearchStrategy.ANCESTORS");
    10. beanFactory = (ConfigurableListableBeanFactory) parent;
    11. }
    12. MatchResult result = new MatchResult();
    13. Set<String> beansIgnoredByType = getNamesOfBeansIgnoredByType(classLoader, beanFactory, considerHierarchy,
    14. spec.getIgnoredTypes(), parameterizedContainers);
    15. for (String type : spec.getTypes()) {
    16. Collection<String> typeMatches = getBeanNamesForType(classLoader, considerHierarchy, beanFactory, type,
    17. parameterizedContainers);
    18. typeMatches.removeAll(beansIgnoredByType);
    19. if (typeMatches.isEmpty()) {
    20. result.recordUnmatchedType(type);
    21. }
    22. else {
    23. result.recordMatchedType(type, typeMatches);
    24. }
    25. }
    26. for (String annotation : spec.getAnnotations()) {
    27. Set<String> annotationMatches = getBeanNamesForAnnotation(classLoader, beanFactory, annotation,
    28. considerHierarchy);
    29. annotationMatches.removeAll(beansIgnoredByType);
    30. if (annotationMatches.isEmpty()) {
    31. result.recordUnmatchedAnnotation(annotation);
    32. }
    33. else {
    34. result.recordMatchedAnnotation(annotation, annotationMatches);
    35. }
    36. }
    37. for (String beanName : spec.getNames()) {
    38. if (!beansIgnoredByType.contains(beanName) && containsBean(beanFactory, beanName, considerHierarchy)) {
    39. result.recordMatchedName(beanName);
    40. }
    41. else {
    42. result.recordUnmatchedName(beanName);
    43. }
    44. }
    45. return result;
    46. }

    这里逻辑看起来比较复杂,但实际上就做了两件事,首先通过
    getNamesOfBeansIgnoredByType方法调用beanFactory.getBeanNamesForType拿到容器中对应的Bean实例,然后根据返回的结果判断哪些Bean存在,哪些Bean不存在(Condition注解中是可以配置多个值的)并返回MatchResult对象,而MatchResult中只要有一个Bean没有匹配上就返回false,也就决定了当前Bean是否需要实例化。

    总结

    本篇分析了SpringBoot核心原理的实现,通过本篇相信读者也将能更加熟练地使用和扩展SpringBoot。另外还有一些常用的组件我没有展开分析,如事务、MVC、监听器的自动配置,这些我们有了Spring源码基础的话下来看一下就明白了,这里就不赘述了。最后读者可以思考一下我们应该如何自定义starter启动器,相信看完本篇应该难不倒你。

  • 相关阅读:
    著名书画家、中国书画院院士李适中
    网络编程
    【狂神说Java】Mybatis学习笔记(上)
    mysql 学习笔记-窗口函数之序号函数
    利用python下的matplotlib库绘制能突出显示的饼状图
    lasso 回归教程 glnmet包
    手工测试如何转向自动化测试?字节5年自动化经验浅谈一下...
    【Android笔记08】Android基本的UI控件(ImageButton、RadioButton、CheckBox、Switch)
    在Go中如何正确重试请求
    PostgreSQL 数据库中查找阻塞和被阻塞的进程
  • 原文地址:https://blog.csdn.net/Java_zhujia/article/details/127765121