springboot——自动配置
在日记(2)中提到过,@SpringBootApplication由以下三个注解组合而成:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
1. @SpringBootConfiguration
该注解就是@Configuration,代表的当前是一个配置类。(所以说明MainApplication本质上也是一个配置类。)
2. @ComponentScan
定义包扫描的规则,然后会自动扫描包路径下面的所有被@Controller、@Service、@Repository、@Component 注解标识的类,然后装配到Spring容器中。
@ComponentScan("目录")
以上为指定特定路径的最基本语法,也可以通过集合的方式进行多个目录查找。
注意:@ComponentScan默认扫描所在类及其所有子包,如果指定扫描目录将不会扫描所在类及其子包。
通过filter属性进行筛选
FilterType.ANNOTATION:按照注解
FilterType.ASSIGNABLE_TYPE:按照给定的类型;
FilterType.ASPECTJ:使用ASPECTJ表达式
FilterType.REGEX:使用正则指定
FilterType.CUSTOM:使用自定义规则
classes:指定过滤的类
例如
@ComponentScan(value = "com.spring.annotation",excludeFilters = {
@ComponentScan.Filter(type=FilterType.ANNOTATION,classes={Controller.class})
})
@ComponentScan.Filter(type=FilterType.ANNOTATION,classes={Controller.class})中的type指定按照何种规则进行筛选,class指定具体筛选的规则。
3. @EnableAutoConfiguration
@EnableAutoConfiguration由以下两个注解构成:
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
(1)@AutoConfigurationPackage
该注解的作用是将SpringBoot主配置类所在的包及其下面的所有子包里面的所有组件扫描到 Spring 容器中
(2)@Import({AutoConfigurationImportSelector.class})
1、利用getAutoConfigurationEntry(annotationMetadata);该方法的作用就是告诉 Spring容器需要导入什么组件,并以 String[] 的形式返回全类名
2、调用List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes)获取到所有需要导入到容器中的配置类
3、利用工厂加载 Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader);得到所有的组件
4、从META-INF/spring.factories位置来加载一个文件。
默认扫描我们当前系统里面所有META-INF/spring.factories位置的文件
spring-boot-autoconfigure-2.3.4.RELEASE.jar包里面也有META-INF/spring.factories
详情可以参考这里
按需加载:虽然127个场景的所有自动配置启动的时候默认全部加载,但是按照条件装配规则(@Conditional),最终会按需配置。
本节知识较难理解,笔者仍在摸索。
标签:扫描,springboot,spring,class,FilterType,ComponentScan,开发,注解,日记 From: https://www.cnblogs.com/tarorat/p/17101190.html