
官方解释Springboot:我们对Spring平台和第三方库持固执己见的观点,因此您可以以最小的麻烦开始使用。大多数Spring Boot应用程序需要最少的Spring配置。
为何springboot可以如此便携,则来源于springboot的自动配置,接下来讲解原理。如集成redis来说。
从启动类@SpringBootApplication入手

而此注解下的@EnableAutoConfiguration注解则是自动配置注解。

通过注解再点击

发现有一个select选择器

而此选择器最终会有一个configuration数组被返回。
而这个数组则是通过扫描一个spring.factory来获取的
通过下面代码发现:
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
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.");
return configurations;
}
//最后追溯到这里

结论:springboot自动配置是寻找项目下的spring.factories的文件来实现自动配置
现在,我们找一个redis的factories来看看。

点进此类查看
@Configuration( //申明配置类
proxyBeanMethods = false
)
//判断有无RedisOperations这个类
@ConditionalOnClass({RedisOperations.class})
//配置这个类的参数在RedisProperties.class查找
@EnableConfigurationProperties({RedisProperties.class})
@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
public class RedisAutoConfiguration {
public RedisAutoConfiguration() {
通过作者代码注释,我们可以总结:
此类的注解:
1: 申明是一个配置类
2:判断是否存在RedisOperations ,存在则开始自动注入
3: 自动配置的参数在RedisProperties.class中查找
点击 RedisProperties进入

@ConfigurationProperties判断配置文件有无spring.redis这个前缀。有的话则继续查找参数注入。如:spring.redis.port
所以:当我们在集成redis的时候,只需要导入redis的jar包,并在application.yml下配置了spring.redis.下的参数(如:spring.redis.port 指定端口)。
1:那么springboot会扫描项目是否导入了redis的jar包,则就是刚才的(判断有无RedisOperations这个类)
2:springboot则会去application.yml查找是否添加了spring.redis开头的配置。有则在初始化redis的时候将配置加载进去。
网友评论