SpringBoot 启动类的原理

SpringBoot启动类上使用 @SpringBootApplication注解,该注解是一个组合注解,包含多个其它注解。和类定义(SpringApplication.run)要揭开 SpringBoot的神秘面纱,我们要从这两位开始就可以了。

1 @SpringBootApplication
2 public class MySpringbootApplication {
3     public static void main(String[] args) {
4         SpringApplication.run(MySpringbootApplication.class, args);
5     }
6 }

@SpringBootApplication


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

@SpringBootApplication 注解上标有三个注解@SpringBootConfiguration 、@EnableAutoConfiguration 、@ComponentScan。其它四个注解用来声明 SpringBootAppliction 为一个注解。

@SpringBootConfiguration

1 @Target({ElementType.TYPE})
2 @Retention(RetentionPolicy.RUNTIME)
3 @Documented
4 @Configuration
5 public @interface SpringBootConfiguration {

@SpringBootConfiguration 注解中没有定义任何属性信息,而该注解上有一个注解 @Configuration,用于标识配置类。所以 @SpringBootConfiguration注解的功能和 @Configuration注解的功能相同,用于标识配置类,与 @Bean搭配使用,一个带有 @Bean的注解方法将返回一个对象,该对象应该被注册为在 Spring应用程序上下文中的 bean。如下案例:

1 @Configuration 
2 public class Conf { 
3       @Bean 
4       public Car car() { 
5           return new Car(); 
6       }
7 }

@ComponentScan


@ComponentScan 这个注解在 Spring中很重要,它对应 XML配置中的元素,@ComponentScan的功能其实就是自动扫描并加载符合条件的组件(比如 @Component和 @Repository等)或者 bean定义,最终将这些 bean定义加载到 IoC容器中。我们可以通过 basePackages等属性来细粒度的定制 @ComponentScan自动扫描的范围,如果不指定,则默认 Spring框架实现会从声明 @ComponentScan所在类的 package进行扫描。注:所以 SpringBoot的启动类最好是放在root package下,因为默认不指定basePackages。

@EnableAutoConfiguration

1 @Target({ElementType.TYPE})
2 @Retention(RetentionPolicy.RUNTIME)
3 @Documented
4 @Inherited
5 @AutoConfigurationPackage
6 @Import({AutoConfigurationImportSelector.class})
7 public @interface EnableAutoConfiguration {

个人感觉 @EnableAutoConfiguration这个 Annotation最为重要,Spring框架提供的各种名字为@Enable开头的Annotation,借助 @Import的支持,收集和注册特定场景相关的 bean定义。@EnableAutoConfiguration也是借助 @Import的帮助,将所有符合自动配置条件的 bean定义加载到IoC容器。@EnableAutoConfiguration注解上标注了两个注解,@AutoConfigurationPackage@Import@Import 注解在 SpringIOC一些注解的源码中比较常见,主要用来给容器导入目标bean。这里 @Import注解给容器导入的组件用于自动配置:AutoConfigurationImportSelector ; 而 @AutoConfigurationPackage注解是Spring自定义的注解,用于将主配置类所在的包作为自动配置的包进行管理。

@AutoConfigurationPackage

 1 package org.springframework.boot.autoconfigure;
 2 
 3 @Target({ElementType.TYPE})
 4 @Retention(RetentionPolicy.RUNTIME)
 5 @Documented
 6 @Inherited
 7 @Import({Registrar.class})
 8 public @interface AutoConfigurationPackage {
 9     String[] basePackages() default {};
10     Class<?>[] basePackageClasses() default {};
11 }

@AutoConfigurationPackage 注解上的 @Import注解,给容器导入了 Registrar组件

Registrar

 1 static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
 2     Registrar() {
 3     }
 4 
 5     public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
 6         AutoConfigurationPackages.register(registry, (String[])(new AutoConfigurationPackages.PackageImports(metadata)).getPackageNames().toArray(new String[0]));
 7     }
 8 
 9     public Set<Object> determineImports(AnnotationMetadata metadata) {
10         return Collections.singleton(new AutoConfigurationPackages.PackageImports(metadata));
11     }
12 }

Registrar是抽象类 AutoConfigurationPackages的内部静态类,Registrar内的 registerBeanDefinitions()方法负责将注解所在的包及其子包下的所有组件注册进容器。这也是为什么 SpringBoot的启动类要在其他类的父包或在同一个包中。

AutoConfigurationImportSelector

public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {

借助AutoConfigurationImportSelector,@EnableAutoConfiguration可以帮助 SpringBoot应用将所有符合条件的 @Configuration配置都加载到当前 SpringBoot创建的 IoC容器中。借助于 Spring框架原有的一个工具类:SpringFactoriesLoader,@EnableAutoConfiguration的自动配置功能才得以大功告成!

SpringFactoriesLoader属于 Spring框架私有的一种扩展方案,其主要功能就是从指定的配置文件 META-INF/spring.factories 加载配置。

1 public abstract class SpringFactoriesLoader {
2     public static <T> List<T> loadFactories(Class<T> factoryClass, ClassLoader classLoader) {
3         ......
4     }
5     public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
6         ......
7     }
8 }

配合 @EnableAutoConfiguration使用的话,它更多是提供一种配置查找的功能支持,即根据 @EnableAutoConfiguration的完整类名 org.springframework.boot.autoconfigure.EnableAutoConfiguration作为查找的Key,获取对应的一组 @Configuration类。

上图就是从 SpringBoot的 autoconfigure依赖包中的 META-INF/spring.factories配置文件中摘录的一段内容,可以很好地说明问题。

所以,@EnableAutoConfiguration自动配置的魔法骑士就变成了:从 classpath中搜寻所有的 META-INF/spring.factories配置文件,并将其中 org.springframework.boot.autoconfigure.EnableutoConfiguration对应的配置项通过反射(Java Refletion)实例化,为标注了 @Configuration的配置类加载到 IoC容器中。

AutoConfigurationImportSelector 类实现了很多 Aware接口,而 Aware接口的功能是使用一些 Spring内置的实例获取一些想要的信息,如容器信息、环境信息、容器中注册的 bean信息等。而 AutoConfigurationImportSelector 类的作用是将 Spring中已经定义好的自动配置类注入容器中,而实现该功能的方法是 selectImports方法:

selectImports


注册 Spring中定义好的配置类

1 public String[] selectImports(AnnotationMetadata annotationMetadata) {
2     if (!this.isEnabled(annotationMetadata)) {
3         return NO_IMPORTS;
4     } else {
5         AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
6         AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
7         return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
8     }
9 }

@EnableAutoConfigurationSpringBoot根据应用所声明的依赖来对Spring框架进行自动配置。
@SpringBootConfiguration(内部为@Configuration):被标注的类等于在 Spring的 XML配置文件中(applicationContext.xml),装配所有 Bean事务,提供了一个 Spring的上下文环境。
@ComponentScan:组件扫描,可自动发现和装配Bean,默认扫描 SpringApplication的 run方法里的 Booter.class所在的包路径下文件,所以最好将该启动类放到根包路径下。

SpringApplication.run(x.class, args)


SpringApplication的 run方法的实现是 SpringApplication执行流程的主要线路,该方法的主要流程大体可以归纳如下:
【1】如果我们使用的是 SpringApplication的静态 run方法,那么,这个方法里面首先要创建一个 SpringApplication对象实例,然后调用这个创建好的 SpringApplication的实例方法。在 SpringApplication实例初始化的时候,它会提前做几件事情:
     ● 根据 classpath里面是否存在某个特征类(org.springframework.web.context.ConfigurableWebApplicationContext)来决定是否应该创建一个为 Web应用使用的 ApplicationContext类型。
     ● 使用 SpringFactoriesLoader在应用的 classpath中查找并加载所有可用的 ApplicationContextInitializer。
     ● 使用 SpringFactoriesLoader在应用的 classpath中查找并加载所有可用的ApplicationListener。
     ● 推断并设置 main方法的定义类。
【2】SpringApplication完成实例初始化并且完成设置后,就开始执行 run方法的逻辑,首先遍历执行所有通过 SpringFactoriesLoader可以查找到并加载的 SpringApplicationRunListener[接口]。调用它们的 started()方法,告诉这些 SpringApplicationRunListener,“嘿,SpringBoot应用要开始执行咯!”。

 1 public interface SpringApplicationRunListener {
 2     default void starting() {
 3     }
 4 
 5     default void environmentPrepared(ConfigurableEnvironment environment) {
 6     }
 7 
 8     default void contextPrepared(ConfigurableApplicationContext context) {
 9     }
10 
11     default void contextLoaded(ConfigurableApplicationContext context) {
12     }
13 
14     default void started(ConfigurableApplicationContext context) {
15     }
16 
17     default void running(ConfigurableApplicationContext context) {
18     }
19 
20     default void failed(ConfigurableApplicationContext context, Throwable exception) {
21     }
22 }

【3】创建并配置当前 Spring Boot应用将要使用的 Environment(包括配置要使用的 PropertySource以及 Profile)。
【4】遍历调用所有 SpringApplicationRunListener的 environmentPrepared()的方法,告诉他们:“当前 SpringBoot应用使用的 Environment准备好了咯!”。
【5】如果 SpringApplication的 showBanner属性被设置为true,则打印banner。
【6】根据用户是否明确设置了applicationContextClass类型以及初始化阶段的推断结果,决定该为当前 SpringBoot应用创建什么类型的 ApplicationContext并创建完成,然后根据条件决定是否添加 ShutdownHook,决定是否使用自定义的 BeanNameGenerator,决定是否使用自定义的 ResourceLoader,当然,最重要的,将之前准备好的 Environment设置给创建好的 ApplicationContext使用。
【7】ApplicationContext创建好之后,SpringApplication会再次借助 SpringFactoriesLoader,查找并加载 classpath中所有可用的 ApplicationContextInitializer,然后遍历调用这些 ApplicationContextInitializer的 initialize(applicationContext)方法来对已经创建好的 ApplicationContext进行进一步的处理。
【8】遍历调用所有 SpringApplicationRunListener的 contextPrepared()方法。
【9】最核心的一步,将之前通过 @EnableAutoConfiguration获取的所有配置以及其他形式的 IoC容器配置加载到已经准备完毕的 ApplicationContext。
【10】遍历调用所有 SpringApplicationRunListener的 contextLoaded()方法。
【11】调用ApplicationContext的 refresh()方法,完成 IoC容器可用的最后一道工序。
【12】查找当前 ApplicationContext中是否注册有 CommandLineRunner,如果有,则遍历执行它们。
【13】正常情况下,遍历执行SpringApplicationRunListener的finished()方法、(如果整个过程出现异常,则依然调用所有SpringApplicationRunListener的finished()方法,只不过这种情况下会将异常信息一并传入处理)

去除事件通知点后,整个流程如下:

调试一个 SpringBoot启动程序为例,参考流程中主要类类图,来分析其启动逻辑和自动化配置原理。

上图为 SpringBoot启动结构图,我们发现启动流程主要分为三个部分,第一部分进行 SpringApplication的初始化模块,配置一些基本的环境变量、资源、构造器、监听器,第二部分实现了应用具体的启动方案,包括启动流程的监听模块、加载配置环境模块、及核心的创建上下文环境模块,第三部分是自动化配置模块,该模块作为 springboot自动配置核心,在后面的分析中会详细讨论。在下面的启动程序中我们会串联起结构中的主要功能。

SpringBoot启动类


进入 run() 方法,run()方法创建了一个 SpringApplication实例并调用其 run()方法。

1 public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
2     return (new SpringApplication(primarySources)).run(args);
3 }

SpringApplication 构造器主要为 SpringApplication对象赋一些初值。构造函数执行完毕后,回到 run()方法

 1 public ConfigurableApplicationContext run(String... args) {
 2     StopWatch stopWatch = new StopWatch();
 3     stopWatch.start();
 4     ConfigurableApplicationContext context = null;
 5     Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
 6     this.configureHeadlessProperty();
 7     SpringApplicationRunListeners listeners = this.getRunListeners(args);
 8     listeners.starting();
 9 
10     Collection exceptionReporters;
11     try {
12         ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
13         ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
14         this.configureIgnoreBeanInfo(environment);
15         Banner printedBanner = this.printBanner(environment);
16         context = this.createApplicationContext();
17         exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
18         this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
19         this.refreshContext(context);
20         this.afterRefresh(context, applicationArguments);
21         stopWatch.stop();
22         if (this.logStartupInfo) {
23             (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
24         }
25 
26         listeners.started(context);
27         this.callRunners(context, applicationArguments);
28     } catch (Throwable var10) {
29         this.handleRunFailure(context, var10, exceptionReporters, listeners);
30         throw new IllegalStateException(var10);
31     }
32 
33     try {
34         listeners.running(context);
35         return context;
36     } catch (Throwable var9) {
37         this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);
38         throw new IllegalStateException(var9);
39     }
40 }

该方法中实现了如下几个关键步骤:
【1】创建了应用的监听器 SpringApplicationRunListeners并开始监听;
【2】加载 SpringBoot配置环境(ConfigurableEnvironment),如果是通过 web容器发布,会加载 StandardEnvironment,其最终也是继承了 ConfigurableEnvironment,类图如下:

可以看出,*Environment最终都实现了 PropertyResolver接口,我们平时通过 environment对象获取配置文件中指定 Key对应的 value方法时,就是调用了 propertyResolver接口的 getProperty方法;
【3】配置环境(Environment)加入到监听器对象中(SpringApplicationRunListeners);
【4】创建 run方法的返回对象:ConfigurableApplicationContext(应用配置上下文),我们可以看一下创建方法:

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

会先获取显式设置的应用上下文(applicationContextClass),如果不存在,再加载默认的环境配置(通过是否是web environment判断),默认选择 AnnotationConfigApplicationContext注解上下文(通过扫描所有注解类来加载bean),最后通过 BeanUtils实例化上下文对象,并返回。

ConfigurableApplicationContext 类图如下:

主要看其继承的两个方向:
LifeCycle:生命周期类,定义了start启动、stop结束、isRunning是否运行中等生命周期空值方法;
ApplicationContext:应用上下文类,其主要继承了 beanFactory(bean的工厂类);
【5】回到 run方法内,prepareContext方法将listeners、environment、applicationArguments、banner等重要组件与上下文对象关联;
【6】接下来的 refreshContext(context)方法(初始化方法如下)将是实现 spring-boot-starter-*(mybatis、redis等)自动化配置的关键,包括 spring.factories的加载,bean的实例化等核心工作。SpringIOC源码 refresh 方法链接 有兴趣的可以看下。

 1 private void refreshContext(ConfigurableApplicationContext context) {
 2     this.refresh((ApplicationContext)context);
 3 }
 4 
 5 //进入 refresh 方法,IOC容器着重分析的方法
 6 public void refresh() throws BeansException, IllegalStateException {
 7     synchronized(this.startupShutdownMonitor) {
 8         this.prepareRefresh();
 9         ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
10         this.prepareBeanFactory(beanFactory);
11 
12         try {
13             this.postProcessBeanFactory(beanFactory);
14             this.invokeBeanFactoryPostProcessors(beanFactory);
15             this.registerBeanPostProcessors(beanFactory);
16             this.initMessageSource();
17             this.initApplicationEventMulticaster();
18             this.onRefresh();
19             this.registerListeners();
20             this.finishBeanFactoryInitialization(beanFactory);
21             this.finishRefresh();
22         } catch (BeansException var9) {
23             if (this.logger.isWarnEnabled()) {
24                 this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
25             }
26 
27             this.destroyBeans();
28             this.cancelRefresh(var9);
29             throw var9;
30         } finally {
31             this.resetCommonCaches();
32         }
33 
34     }
35 }

配置结束后,SpringBoot做了一些基本的收尾工作,返回了应用环境上下文。回顾整体流程,SpringBoot的启动,主要创建了配置环境(environment)、事件监听(listeners)、应用上下文(applicationContext),并基于以上条件,在容器中开始实例化我们需要的Bean,至此,通过 SpringBoot启动的程序已经构造完成,接下来我们来探讨自动化配置是如何实现。

自动化配置


之前的启动结构图中,我们注意到无论是应用初始化还是具体的执行过程,都调用了 SpringBoot自动配置模块。

SpringBoot 自动配置模块:该配置模块的主要使用到了SpringFactoriesLoader,即 Spring工厂加载器,该对象提供了 loadFactoryNames方法,入参为 factoryClass和 classLoader,即需要传入上图中的工厂类名称和对应的类加载器,方法会根据指定的 classLoader,加载该类加器搜索路径下的指定文件,即spring.factories文件,传入的工厂类为接口,而文件中对应的类则是接口的实现类,或最终作为实现类,所以文件中一般为如下图这种一对多的类名集合,获取到这些实现类的类名后,loadFactoryNames方法返回类名集合,方法调用方得到这些集合后,再通过反射获取这些类的类对象、构造方法,最终生成实例。

 1 # PropertySource Loaders
 2 org.springframework.boot.env.PropertySourceLoader=\
 3 org.springframework.boot.env.PropertiesPropertySourceLoader,\
 4 org.springframework.boot.env.YamlPropertySourceLoader
 5 
 6 # Run Listeners
 7 org.springframework.boot.SpringApplicationRunListener=\
 8 org.springframework.boot.context.event.EventPublishingRunListener
 9 
10 # Error Reporters
11 org.springframework.boot.SpringBootExceptionReporter=\
12 org.springframework.boot.diagnostics.FailureAnalyzers
13 
14 # Application Context Initializers
15 org.springframework.context.ApplicationContextInitializer=\
16 org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\

下图有助于我们形象理解自动配置流程。

mybatis-spring-boot-starter(starter详细内容链接)、spring-boot-starter-web等组件的 META-INF文件下均含有 spring.factories文件,自动配置模块中,SpringFactoriesLoader收集到文件中的类全名并返回一个类全名的数组,返回的类全名通过反射被实例化,就形成了具体的工厂实例,工厂实例来生成组件具体需要的bean。之前我们提到了 EnableAutoConfiguration注解,其类图如下:

可以发现其最终实现了 ImportSelector(选择器)和 BeanClassLoaderAware(bean类加载器中间件),重点关注一下 AutoConfigurationImportSelector的 selectImports方法。

 1 public String[] selectImports(AnnotationMetadata annotationMetadata) {
 2     if (!this.isEnabled(annotationMetadata)) {
 3         return NO_IMPORTS;
 4     } else {
 5         AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);
 6         return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
 7     }
 8 }
 9 
10 protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
11     if (!this.isEnabled(annotationMetadata)) {
12         return EMPTY_ENTRY;
13     } else {
14         AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
15         List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
16         configurations = this.removeDuplicates(configurations);
17         Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
18         this.checkExcludedClasses(configurations, exclusions);
19         configurations.removeAll(exclusions);
20         configurations = this.getConfigurationClassFilter().filter(configurations);
21         this.fireAutoConfigurationImportEvents(configurations, exclusions);
22         return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
23     }
24 }

该方法在 SpringBoot启动流程 Bean实例化前被执行,返回要实例化的类信息列表。如果获取到类信息,Spring自然可以通过类加载器将类加载到 jvm中,现在我们已经通过SpringBoot的 starter依赖方式依赖了我们需要的组件,那么这些组建的类信息在 select方法中也是可以被获取到的。

1 protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
2     List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
3     Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
4     return configurations;
5 }

该方法中的 getCandidateConfigurations方法,其返回一个自动配置类的类名列表,方法调用了 loadFactoryNames方法,查看该方法:

1 public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
2     String factoryTypeName = factoryType.getName();
3     return (List)loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
4 }

在上面的代码可以看到自动配置器会根据传入的 factoryType.getName()到项目系统路径下所有的 spring.factories文件中找到相应的key,从而加载里面的类。我们就选取这个 mybatis-spring-boot-autoconfigure下的 spring.factories文件

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration

进入org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration中,主要看一下类头:

1 @Configuration
2 @ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
3 @ConditionalOnBean({DataSource.class})
4 @EnableConfigurationProperties({MybatisProperties.class})
5 @AutoConfigureAfter({DataSourceAutoConfiguration.class})
6 public class MybatisAutoConfiguration {

@Configuration,俨然是一个通过注解标注的 SpringBean;
@ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class})这个注解的意思是:当存在 SqlSessionFactory.class, SqlSessionFactoryBean.class这两个类时才解析 MybatisAutoConfiguration配置类,否则不解析这一个配置类,make sence,我们需要mybatis为我们返回会话对象,就必须有会话工厂相关类;
@CondtionalOnBean(DataSource.class):只有处理已经被声明为bean的dataSource;
@ConditionalOnMissingBean(MapperFactoryBean.class)这个注解的意思是如果容器中不存在name指定的bean则创建bean注入,否则不执行(该类源码较长,篇幅限制不全粘贴);

以上配置可以保证 sqlSessionFactory、sqlSessionTemplate、dataSource等 mybatis所需的组件均可被自动配置,@Configuration注解已经提供了 Spring的上下文环境,所以以上组件的配置方式与 Spring启动时通过 mybatis.xml文件进行配置起到一个效果。通过分析我们可以发现,只要一个基于 SpringBoot项目的类路径下存在 SqlSessionFactory.class, SqlSessionFactoryBean.class,并且容器中已经注册了 dataSourceBean,就可以触发自动化配置,意思说我们只要在 maven的项目中加入了 mybatis所需要的若干依赖,就可以触发自动配置,但引入 mybatis原生依赖的话,每集成一个功能都要去修改其自动化配置类,那就得不到开箱即用的效果了。所以 SpringBoot为我们提供了统一的 starter可以直接配置好相关的类,触发自动配置所需的依赖(mybatis)如下:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
    <version>2.1.0.RELEASE</version>
</dependency>

这里是截取的 mybatis-spring-boot-starter的源码中 pom.xml文件中所有依赖:

 1 <dependencies>
 2     <dependency>
 3       <groupId>org.springframework.boot</groupId>
 4       <artifactId>spring-boot-starter</artifactId>
 5     </dependency>
 6     <dependency>
 7       <groupId>org.springframework.boot</groupId>
 8       <artifactId>spring-boot-starter-jdbc</artifactId>
 9     </dependency>
10     <dependency>
11       <groupId>org.mybatis.spring.boot</groupId>
12       <artifactId>mybatis-spring-boot-autoconfigure</artifactId>
13     </dependency>
14     <dependency>
15       <groupId>org.mybatis</groupId>
16       <artifactId>mybatis</artifactId>
17     </dependency>
18     <dependency>
19       <groupId>org.mybatis</groupId>
20       <artifactId>mybatis-spring</artifactId>
21     </dependency>
22 </dependencies>

因为 maven依赖的传递性,我们只要依赖 starter就可以依赖到所有需要自动配置的类,实现开箱即用的功能。也体现出 Springboot简化了 Spring框架带来的大量 XML配置以及复杂的依赖管理,让开发人员可以更加关注业务逻辑的开发。

总结


配置文件定义属性[@Configuration],自动装配到所属的配置类中,然后通过动态代理进入 spring容器中。

 

posted @ 2020-11-14 12:08  Java程序员进阶  阅读(150)  评论(0编辑  收藏  举报