咱们了解到 Spring Boot 提供了不少开箱即用的依赖模块,开发者只要在 Maven 的 pom 文件中添加相关依赖后,Spring Boot 就会针对这个应用自动建立和注入须要的 Spring Bean 到上下文中。spring
这篇,咱们以 FreeMarker 的自动配置为例,重点讲解工做原理与加载过程。由于 FreeMarker 相对而言比较简单,Spring Boot 源码中只有三个类,因此做为案例相对而言比较好理解。springboot
EnableAutoConfiguration 帮助咱们作了什么
你还记得 @EnableAutoConfiguration 注解么?app
咱们先来回顾下。ide
@RestController @EnableAutoConfiguration @ComponentScan(basePackages = { "com.lianggzone.springboot" }) public class WebMain { public static void main(String[] args) throws Exception { SpringApplication.run(WebMain.class, args); } }
那么,如今咱们剖析下 @EnableAutoConfiguration 的源码。源码分析
这里,关键在于 @Import 注解导入的 EnableAutoConfigurationImportSelector 类中最为关键的是 getCandidateConfigurations 方法中经过 SpringFactoriesLoader.loadFactoryNames 扫描 spring.factories 文件。spa
如今,咱们在来看下 SpringFactoriesLoader 源码。3d
忽然,你是否是发现 spring.factories 文件是至关重要呢?对的,Spring Boot 经过扫描这个文件中的内容,判断有哪些自动配置。以 FreeMarker 为例,咱们来看下它是如何配置的。code
因此,Spring Boot 经过扫描 spring.factories 文件中的 EnableAutoConfiguration 参数中有哪些自动配置并进行加载。blog
配置参数类 – FreeMarkerProperties
这里的配置参数,能够经过application.properties 中直接设置。咱们发现,它的前缀必须是 spring.freemarker。开发
自动配置类 – FreeMarkerAutoConfiguration
核心注解
在《 Spring Boot 揭秘与实战 源码分析 - 开箱即用,内藏玄机 》一文,有提到 @ConditionalOnClass 参数中对应的类在 classpath 目录下存在时,才会去解析对应的配置类,不然不解析该注解修饰的配置类。
Spring Boot 内部提供了不少自动化配置的类,例如,RedisAutoConfiguration 、MongoRepositoriesAutoConfiguration 、ElasticsearchAutoConfiguration , 这些自动化配置的类会判断 classpath 中是否存在本身须要的那个类,若是存在则会自动配置相关的配置,不然就不会自动配置,所以,开发者在 Maven 的 pom 文件中添加相关依赖后,这些依赖就会下载不少 jar 包到 classpath 中,有了这些 lib 就会触发自动化配置,因此,咱们就能很便捷地使用对于的模块功能了。
此外,还有一个主要的注解是 @EnableConfigurationProperties ,主要用来加载咱们上面提到的配置参数类。
注入 Bean
这个源码很是好理解,我主要想讲2个注解。
第一注解是,@ConditionalOnMissingBean(name = “freeMarkerViewResolver”),指定当容器没有指定Bean的状况下的处理。
第二注解是,@ConditionalOnProperty,指定的属性是否有指定的值的处理,换句话说,若是在application.properties 没有配置,默认为 true,即条件符合。