SpringBoot自动配置原理
对于SpringBoot环境,配置起来相对于maven项目更加的简单,不需要配置大量的繁琐的pom坐标,简化了项目的开发过程,提高了我们的开发相率。
那么,它是如何实现自动配置呢?
1.1三个重要的注解
@SpringBootApplication
public class SpringBootMailApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMailApplication.class, args);
}
}
由上面的代码可以看出,在使用main()启动SpringBoot时,仅仅只有一个@SpringBootApplication注解,其底层的源码如下图所示
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
}
@SpringBootConfiguration:它的底层是@Configuration注解由此可知提示可以通过JavaConfig的方式进行配置的。
@EnableAutoConfiguration:该注解实现了开启自动配置功能
@ComponentScan:进行扫描将@Controller/@Service/@Component/@Repository等注解加载到IOC容器中。
1.2EnableAutoConfiguration
众所周知,SpringBoot可以为我们简化很多的配置,那么它是如何实现这样的功能的,这是就体现出了@EnableAutoConfiguration注解的作用了。
这个注解可以帮助我们自动载入应用程序所需要的默认配置
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
Class<?>[] exclude() default {};
String[] excludeName() default {};
}
通过查看其底层的源码可以发现,有两个比较重要的注解。
@AutoConfigurationPackage:自动配置包
@Import:将组件导入IOC容器中
1.2.1AutoConfigurationPackage
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({AutoConfigurationPackage.Registrar.class})
public @interface AutoConfigurationPackage {
}
通过观察其底层的源码,发现它所依靠的还是@Import注解,进入底层查看发现以下代码。
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
register(registry, new PackageImport(metadata).getPackageName());
}
默认情况下是将:主配置类的
(@SpringBootApplication)的所在的包及其子包里面的组件扫描到Spring容器中。
在这里重点要区分一下,@AutoConfigurationPackage它是当你使用了Spring Data JPA时,可能会在实体类上写@Entity注解,这个注解由@AutoConfigurationPackage扫描并加载的,但是我们平时开发使用的@Controller、@Service、@Component、@Repository这些注解是通过@ComponentScan来扫描并加载的,由此得出两个注解所扫描的对象是不一样的。
1.2.2Import
查看@Import({AutoConfigurationImportSelector.class})
这句代码,进入AutoConfigurationImportSelector.class
源码中,查看他具体实现的是什么:
protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
if (!this.isEnabled(annotationMetadata))
{return EMPTY_ENTRY;
}
else {
AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
configurations = this.removeDuplicates(configurations);
Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
this.checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
configurations = this.getConfigurationClassFilter().filter(configurations);
this.fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
}
}
可以看出获取到很多的配置信息,进入getCandidateConfigurations
()方法
protected Class<?> getAnnotationClass() {
return EnableAutoConfiguration.class;
}
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = new ArrayList(SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader()));
ImportCandidates.load(AutoConfiguration.class, this.getBeanClassLoader()).forEach(configurations::add);
Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories nor in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. If you are using a custom packaging, make sure that file is correct.");
return configurations;
}
这里面包装了一层,目前可以看出是通过SpringFactoriesLoader加载的,进入loadFactoryNames中
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
ClassLoader classLoaderToUse = classLoader;
if (classLoader == null) {
classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
}
String factoryTypeName = factoryType.getName();
return (List)loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
}
private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
Map<String, List<String>> result = (Map)cache.get(classLoader);
if (result != null) {
return result;
} else {
HashMap result = new HashMap();
try {
Enumeration urls = classLoader.getResources("META-INF/spring.factories");
while(urls.hasMoreElements()) {
URL url = (URL)urls.nextElement();
UrlResource resource = new UrlResource(url);
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
Iterator var6 = properties.entrySet().iterator();
while(var6.hasNext()) {
Entry<?, ?> entry = (Entry)var6.next();
String factoryTypeName = ((String)entry.getKey()).trim();
String[] factoryImplementationNames = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
String[] var10 = factoryImplementationNames;
int var11 = factoryImplementationNames.length;
for(int var12 = 0; var12 < var11; ++var12) {
String factoryImplementationName = var10[var12];
((List)result.computeIfAbsent(factoryTypeName, (key) -> {
return new ArrayList();
})).add(factoryImplementationName.trim());
}
}
}
result.replaceAll((factoryType, implementations) -> {
return (List)implementations.stream().distinct().collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
});
cache.put(classLoader, result);
return result;
} catch (IOException var14) {
throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var14);
}
}
}
-
FACTORIES_RESOURCE_LOCATION
的值是META-INF/spring.factories
-
Spring启动的时候会扫描所有jar路径下的
META-INF/spring.factories
,将其文件包装成Properties对象 -
从Properties对象获取到key值为
EnableAutoConfiguration
的数据,然后添加到容器里边1.3总结
@SpringBootApplication等于以下几个注解:
@SpringBootConfiguration @EnableAutoConfiguration @ComponentScan
@EnableAutoConfiguration是用来启动自动配置的,
META-INF/spring.factories
文件的信息,然后筛选出以EnableAutoConfiguration
为key的数据,加载到IOC容器中,实现自动配置功能!