Spring Boot 手摸手系列-自动配置原理(一)

/ 2020-08-01 / 1187人浏览 / 0人评论

上一篇文章 Spring Boot 手摸手系列-hello word(二)要点分析 ,提到过 @EnableAutoConfiguration 表示开启自动配置功能。 下面就做下详细分析:

我们的配置文件 application.yml 或者 application.properties, 为什么很多属性配置之后就能立即生效呢?
这个就得益于springboot的自动配置,springboot会将很多配置类自动为我们注入到spring容器中,

1、 springboot主程序启动时开启自动配置 @EnableAutoConfiguration

@SpringBootApplication
public class StartApplication {
	public static void main(String[] args) {
		// springboot 应用启动
		SpringApplication.run(StartApplication.class, args);
	}
}

@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 {

2、 @EnableAutoConfiguration 通过 AutoConfigurationImportSelector 导入( @Import )组件
AutoConfigurationImportSelector 是一个组件选择器;它筛选出一些组件,然后注入到ioc容器中;那么它如何筛选?
直接看它源码:

@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
	if (!isEnabled(annotationMetadata)) {
		return NO_IMPORTS;
	}
	AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
				.loadMetadata(this.beanClassLoader);
	AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(autoConfigurationMetadata,
				annotationMetadata);
	return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}

/**
 * Return the {@link AutoConfigurationEntry} based on the {@link AnnotationMetadata}
 * of the importing {@link Configuration @Configuration} class.
 * @param autoConfigurationMetadata the auto-configuration metadata
 * @param annotationMetadata the annotation metadata of the configuration class
 * @return the auto-configurations that should be imported
 */
protected AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata,AnnotationMetadata annotationMetadata) {
	if (!isEnabled(annotationMetadata)) {
		return EMPTY_ENTRY;
	}
	AnnotationAttributes attributes = getAttributes(annotationMetadata);
	List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
	configurations = removeDuplicates(configurations);
	Set<String> exclusions = getExclusions(annotationMetadata, attributes);
	checkExcludedClasses(configurations, exclusions);
	configurations.removeAll(exclusions);
	configurations = filter(configurations, autoConfigurationMetadata);
	fireAutoConfigurationImportEvents(configurations, exclusions);
	return new AutoConfigurationEntry(configurations, exclusions);
}

我们可以看到 selectImports 返回了一个sting[] ,这个字符串数组就是要注入的类全类名。然而实际真正获取全类名数组的方法是 :
List configurations = getCandidateConfigurations(annotationMetadata, attributes);
getCandidateConfigurations 方法是去获取候选的配置

List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),getBeanClassLoader());

查看 SpringFactoriesLoader.loadFactoryNames() 源码,我们发现如下代码;它是扫描所有jar包类路径下META-INF/spring.factories;

public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
	String factoryTypeName = factoryType.getName();
	return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}

loadSpringFactories(classLoader) 看它源码如下:

Enumeration<URL> urls = (classLoader != null ?
					classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
					ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));

FACTORIES_RESOURCE_LOCATION 点过去一看其实就是 META-INF/spring.factories

/**
 * The location to look for factories.
 * <p>Can be present in multiple JAR files.
 */
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

同时看源码我们得以见得,通过Enumeration urls 我们得到了Properties properties ;这个过程其实就是将扫描到的内容转成 Properties对象。

URL url = urls.nextElement();
                 UrlResource resource = new UrlResource(url);
                 Properties properties = PropertiesLoaderUtils.loadProperties(resource);

而获取的所有 Properties 对象
loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList()); 获取得到一个 叫 factoryTypeName 的组件;
factoryTypeName 咋来的呢,上面提到的 getSpringFactoriesLoaderFactoryClass()我们打开一看其实就是EnableAutoConfiguration.class

所以这里简单的概括其实就是 从 Properties 对象中 获取 EnableAutoConfiguration.class 类名对应的值,然后把它们添加到容器中。

3、
EnableAutoConfiguration.class 在 spring-boot-autoconfigur jar 包下的 META-INF/spring.factories  可以找到对应的值。如下图:

而在将 类路径下 META-INF/spring.factories 中含有 EnableAutoConfiguration.class 的值加入到容器中,具体操作是什么呢?
请看下文 Spring Boot 手摸手系列-自动配置原理(二)

全部评论