在使用SpringBoot时,启动类会使用@SpringBootApplication这个注解(如下):
@SpringBootApplication //是SpringBoot的主配置类
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}
点击这个注解源码发现有三个注解@SpringBootConfiguration @EnableAutoConfiguration @ComponentScan,(代码如下所示),我们可以认为@SpringBootApplication可被@SpringBootConfiguration @EnableAutoConfiguration @ComponentScan三个注解代替,即启动类上可以标注这三个注解(不是说其他的注解没用,只是相对这三个对springboot而言作用很小)。
@Target(ElementType.TYPE) //设置当前注解可以标记在哪
@Retention(RetentionPolicy.RUNTIME) //当注解标注的类编译以什么方式保留(会被jvm加载)
@Documented //java doc 会生成注解信息
@Inherited //是否会被继承
@SpringBootConfiguration //表示这是一个Spring Boot的配置类
@EnableAutoConfiguration //SpringBoot开启自动配置,会帮我们自动去加载自动配置类
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
//扫描包,如果没有basePackage指定spring底层会自动扫描当前配置类所有在的包
public @interface SpringBootApplication {
@AliasFor(annotation = EnableAutoConfiguration.class)
Class<?>[] exclude() default {};
而这三个注解跟自动配置有关系的就是@EnableAutoConfiguration了,从名字上也可以看出,点进去看看源码如下:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage//将当前配置类所在包保存在BasePackages的Bean中,供Spring内部使用
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
Class<?>[] exclude() default {};
String[] excludeName() default {};
}
可以看到上面的源代码,有@Import(
AutoConfigurationImportSelector.class),而这个注解就是关键,导入了AutoConfigurationImportSelector类,这个类实现了DeferredImportSelector接口,并且重写了getImportGroup和selectImports方法。
实现了DeferredImportSelector接口的类被用上@Import后,会在spring加载完bean后处理,假如有重写getImportGroup就会使用此函数中的group类,调用他的process方法,再调用这个group类的selectImports方法,如果没有group类会直接调用
AutoConfigurationImportSelector的getImportGroup方法(这是spring源码时执行逻辑),Group类的源码如下:
@Override
public Class<? extends Group> getImportGroup() {
return AutoConfigurationGroup.class;
}
@Override
public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) {
Assert.state(deferredImportSelector instanceof AutoConfigurationImportSelector,
() -> String.format("Only %s implementations are supported, got %s",
AutoConfigurationImportSelector.class.getSimpleName(),
deferredImportSelector.getClass().getName()));
AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector)
.getAutoConfigurationEntry(annotationMetadata);//会加载配置文件的自动配置类
this.autoConfigurationEntries.add(autoConfigurationEntry);//在selectImports中会使用
for (String importClassName : autoConfigurationEntry.getConfigurations()) {
this.entries.putIfAbsent(importClassName, annotationMetadata);//在selectImports中排序用
}
}
@Override
public Iterable<Entry> selectImports() {
if (this.autoConfigurationEntries.isEmpty()) {
return Collections.emptyList();
}
//从自动配置类的集合中获取Exclusions和Configurations
Set<String> allExclusions = this.autoConfigurationEntries.stream()
.map(AutoConfigurationEntry::getExclusions).flatMap(Collection::stream).collect(Collectors.toSet());
Set<String> processedConfigurations = this.autoConfigurationEntries.stream()
.map(AutoConfigurationEntry::getConfigurations).flatMap(Collection::stream)
.collect(Collectors.toCollection(LinkedHashSet::new));
processedConfigurations.removeAll(allExclusions);
return sortAutoConfigurations(processedConfigurations, getAutoConfigurationMetadata()).stream()
.map((importClassName) -> new Entry(this.entries.get(importClassName), importClassName))
.collect(Collectors.toList());//为自动配置类排序
}
下面分析下process函数中调用的getAutoConfigurationEntry方法,源码如下:
protected AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
if (!isEnabled(annotationMetadata)) {
return EMPTY_ENTRY;
}
//获取注解属性信息
AnnotationAttributes attributes = getAttributes(annotationMetadata);
// 从META‐INF/spring.factories中获得所有的自动配置类(包含所有jar及项目自己写的META‐INF/spring.factories)
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
//使用LinkedHashSet排重
configurations = removeDuplicates(configurations);
//根据EnableAutoConfiguration注解中属性,获取不需要自动装配的类名单
Set<String> exclusions = getExclusions(annotationMetadata, attributes);
// 根据:@EnableAutoConfiguration.exclude
// @EnableAutoConfiguration.excludeName
// spring.autoconfigure.exclude 进行排除
checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
//通过读取spring.factories中的OnBeanCondition\OnClassCondition\OnWebApplicationCondition条件注解进行过滤
configurations = getConfigurationClassFilter().filter(configurations);
//添加监听器事件,分别把候选的配置名单,和排除的配置名单传进去做扩展
fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationEntry(configurations, exclusions);
}
自动配置META‐INF/spring.factories格式如下:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.baomidou.mybatisplus.autoconfigure.IdentifierGeneratorAutoConfiguration,\
com.baomidou.mybatisplus.autoconfigure.MybatisPlusLanguageDriverAutoConfiguration,\
com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration
@EnableAutoConfiguration注解通过@SpringBootApplication被间接的标记在了Spring Boot的启动类上。在
MySpringBootApplication.run(...)的内部就会解析@Import注解,执行group的process方法,找到所有JavaConfig自动配置类的全限定名对应的class,然后将所有自动配置类加载到Spring容器中。