在Springboot启动类中的SpringbootApplication注解
包含三个重要子注解:
@SpringBootConfiguration:标志为启动类 @EnableAutoConfiguration:自动装配 @ComponentScan:IOC注解扫描
@EnableAutoConfiguration中的@Import注解的AutoConfigurationImportSelector.class是自动配置类的导入选择器
进入AutoConfigurationImportSelector中发现它实现了DeferredImportSelector
再进入DeferredImportSelector,它又继承了ImportSelector接口
最后进入ImportSelector,里面有个方法:String[] selectImports(AnnotationMetadata importingClassMetadata);
selectImports这个方法就是用来批量注册Bean的,方法的返回值是字符串数组,就是类的全限定名,spring会根据这些全限定类名注册对应的Bean。
在刚才的AutoConfigurationImportSelector中实现了selectImports
最后发现在getCandidateConfigurations方法中通过断言工具的notEmpty方法有个报错信息:No auto configuration classes found in META-INF/spring.factories,即在META-INF/spring.factores中找不到自动配置类
我们去到Springboot自动配置依赖下,点击它的spring.factores中
发现有很多Springboot配置类的全限定名
在Auto Configure下,就是Springboot自动加载的配置类
比如:
这个就是redis的自动配置类,点进去:
这是Springboot帮我们加载了该redis自动配置类。我们就可以导入redis包后,直接注入使用RedisTemplate了。
注意:在RedisAutoConfiguration中,有一个注解@EnableConfigurationProperties({RedisProperties.class})指向了一个读取配置的类RedisProperties。
在RedisProperties中我们发现这些字段就是我们平时在yml中配置的redis的信息,然后类中通过@ConfigurationProperties( prefix = "spring.redis" )去批量读取前缀为spring.redis的配置了
其他的自动配置也是一样的。谨以此记录加深Springboot启动类的理解。