SpringBoot自动配置原理

一、引言

在Spring+SpringMVC框架下,我们需要两个配置文件(一个文件也行哈),来集成Spring和SpringMVC。但使用SpringBoot之后,我们就不需要像之前那样繁琐的配置了,SpringBoot帮我们一站式配置好,这就要归功于SpringBoot的自动配置,下面来探索一下自动配置的原理。

下面这个链接是SpringBoot官方文档,专门介绍了在application.properties配置文件中,可以配置哪些参数,可以参考一下。

https://docs.spring.io/spring-boot/docs/1.5.9.RELEASE/reference/htmlsingle/#common-application-properties

二、自动配置原理

1、SpringBoot启动时,会加载 被@SpringBootApplication注解 修饰的主配置类,而该注解又开启了自动配置功能 @EnableAutoConfiguration;

@Target(ElementType.TYPE)            // 注解的适用范围,其中TYPE用于描述类、接口(包括包注解类型)或enum声明
@Retention(RetentionPolicy.RUNTIME)  // 注解的生命周期,保留到class文件中(三个生命周期)
@Documented                          // 表明这个注解应该被javadoc记录
@Inherited                           // 子类可以继承该注解
@SpringBootConfiguration             // 继承了Configuration,表示当前是注解类
@EnableAutoConfiguration             // 开启springboot的注解功能
@ComponentScan(excludeFilters = {    // 扫描路径设置(具体使用待确认)
			@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
			@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

	@AliasFor(annotation = EnableAutoConfiguration.class)
	Class<?>[] exclude() default {};
	
	@AliasFor(annotation = EnableAutoConfiguration.class)
	String[] excludeName() default {};
	
	@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
	String[] scanBasePackages() default {};
	
	@AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
	Class<?>[] scanBasePackageClasses() default {};

}

虽然定义使用了多个Annotation进行了原信息标注,但实际上重要的只有三个Annotation:

@SpringBootConfiguration:点开查看发现里面是应用了@Configuration
@EnableAutoConfiguration
@ComponentScan

2、@Configuration注解说明

这里的@Configuration不陌生,它就是JavaConfig形式的Spring Ioc容器的配置类使用的那个@Configuration,SpringBoot社区推荐使用基于JavaConfig的配置形式,所以,这里的启动类标注了@Configuration之后,本身其实也是一个IoC容器的配置类。以下两种配置方式等价:

基于XML的配置形式:

<bean id="jdbcTemplate" class="..JDBCTemplate">
    ...
</bean>

基于JavaConfig的配置形式:

	@Configuration
	public class JDBCConfiguration{
	    @Bean
	    public JDBCTemplate jdbcTemplate(){
	        return new JDBCTemplate ();
	    }
	}

任何一个标注了@Bean的方法,其返回值将作为一个bean定义注册到Spring的IoC容器,方法名将默认成该bean定义的id。

3、@ComponentScan

@ComponentScan注解功能:其实就是自动扫描并加载符合条件的组件(比如@Component、@Repository等)或者bean定义,最终将这些bean定义加载到IoC容器中。

我们可以通过basePackages等属性来细粒度的定制@ComponentScan自动扫描的范围,如果不指定,则默认Spring框架实现会从声明@ComponentScan所在类的package进行扫描。

4、@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(AutoConfigurationImportSelector.class)

5、@AutoConfigurationPackage 注解:

点击进入该注解,可以发现:

@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {

}

//注册了一个Bean的定义
static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {

	@Override
	public void registerBeanDefinitions(AnnotationMetadata metadata,
			BeanDefinitionRegistry registry) {
		
		register(registry, new PackageImport(metadata).getPackageName());
	}
}

new PackageImport(metadata).getPackageName(),它其实返回了当前主程序类所在包以及下面所有子包的组件,然后将这些组件注册到Spring容器中。

注意:这里分析可以知道,我们要把将主配置类(@SpringBootApplication标注的类)放在项目的最高级中。

6、@Import注解:
利用AutoConfigurationImportSelector给容器中导入一些组件,在AutoConfigurationImportSelector类中,查看selectImports()函数:

@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
	if (!isEnabled(annotationMetadata)) {
		return NO_IMPORTS;
	}
	AutoConfigurationMetadata autoConfigurationMetadata = 
	AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
	
	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 StringUtils.toStringArray(configurations);
}

查看getCandidateConfigurations()方法

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
		AnnotationAttributes attributes) {

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

该方法扫描所有jar包类路径下 META‐INF/spring.factories,把扫描到的这些文件的内容包装成properties对象,从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加在容器中。

查看loadFactoryNames()方法

private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
	MultiValueMap<String, String> result = cache.get(classLoader);
	if (result != null) {
		return result;
	}

	try {
		Enumeration<URL> urls = (classLoader != null ?
				classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
				ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
		result = new LinkedMultiValueMap<>();
		while (urls.hasMoreElements()) {
			URL url = urls.nextElement();
			UrlResource resource = new UrlResource(url);
			Properties properties = PropertiesLoaderUtils.loadProperties(resource);
			for (Map.Entry<?, ?> entry : properties.entrySet()) {
				List<String> factoryClassNames = Arrays.asList(
						StringUtils.commaDelimitedListToStringArray((String) entry.getValue()));
				result.addAll((String) entry.getKey(), factoryClassNames);
			}
		}
		cache.put(classLoader, result);
		return result;
	}
	catch (IOException ex) {
		throw new IllegalArgumentException("Unable to load factories from location [" +
				FACTORIES_RESOURCE_LOCATION + "]", ex);
	}
}

该方法会将类路径下 META-INF/spring.factories 里面配置的所有EnableAutoConfiguration的值加入到了容器中;

下面是spring-boot-autoconfigure包中的META-INF下的spring.factories文件中的自动配置,其中每一个这样的 xxxAutoConfiguration类都是容器中的一个组件,都加入到容器中,用它们来做自动配置;
在这里插入图片描述

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
……
……
此处略,可自行查看

三、自动配置幕后英雄:SpringFactoriesLoader详解

借助于Spring框架原有的一个工具类:SpringFactoriesLoader的支持,@EnableAutoConfiguration注解智能的自动配置功效才能得以大功告成!

SpringFactoriesLoader属于Spring框架私有的一种扩展方案,其主要功能就是从指定的配置文件META-INF/spring.factories加载配置。

public final class SpringFactoriesLoader {

	public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

	private static final Log logger = LogFactory.getLog(SpringFactoriesLoader.class);

	private static final Map<ClassLoader, MultiValueMap<String, String>> cache = new ConcurrentReferenceHashMap<>();

	private SpringFactoriesLoader() {
	}
	
	public static <T> List<T> loadFactories(Class<T> factoryClass, @Nullable ClassLoader classLoader) {
		
	}

	public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
		
	}

	private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
		
	}

	@SuppressWarnings("unchecked")
	private static <T> T instantiateFactory(String instanceClassName, Class<T> factoryClass, 
	}

}

SpringFactoriesLoader配合@EnableAutoConfiguration使用的话,它更多的是提供一种配置查找的功能支持,即根据@EnableAutoConfiguration的完整类名org.springframework.boot.autoconfigure.EnableAutoConfiguration作为查找的Key,去获取对应的一组@Configuration类。
在这里插入图片描述

上图就是SpringBoot的autoconfigure依赖包中META-INF/spring.factories配置文件中的一段内容。

所以,@EnableAutoConfiguration自动配置就变成了:从classpath中搜寻所有的META-INF/spring.factories配置文件,并将其中org.springframework.boot.autoconfigure.EnableutoConfiguration对应的配置项,通过反射实例化为对应的标注了@Configuration的JavaConfig形式的IoC容器配置类,然后汇总为一个并加载到IoC容器。

四、自动配置原理例子

以HttpEncodingAutoConfiguration(http编码自动配置)为例解释自动配置原理

1、代码
@Configuration
@EnableConfigurationProperties(HttpEncodingProperties.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnClass(CharacterEncodingFilter.class)
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)
public class HttpEncodingAutoConfiguration {

	//已经和SpringBoot的配置文件映射了
	private final HttpEncodingProperties properties;

	//只有一个有参构造器的情况下,参数的值就会从容器中拿
	public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {
		this.properties = properties;
	}

	@Bean	//给容器中添加一个组件,这个组件的某些值需要从properties中获取
	@ConditionalOnMissingBean	//如果容器中没有这个组件,则把该组件加入到容器中
	public CharacterEncodingFilter characterEncodingFilter() {
		CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
		filter.setEncoding(this.properties.getCharset().name());
		filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));
		filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));
		return filter;
	}

	@Bean
	public LocaleCharsetMappingsCustomizer localeCharsetMappingsCustomizer() {
		return new LocaleCharsetMappingsCustomizer(this.properties);
	}

	private static class LocaleCharsetMappingsCustomizer implements
			WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered {

		private final HttpEncodingProperties properties;

		LocaleCharsetMappingsCustomizer(HttpEncodingProperties properties) {
			this.properties = properties;
		}

		@Override
		public void customize(ConfigurableServletWebServerFactory factory) {
			if (this.properties.getMapping() != null) {
				factory.setLocaleCharsetMappings(this.properties.getMapping());
			}
		}

		@Override
		public int getOrder() {
			return 0;
		}
	}
}
2、说明
(1)、@Configuration 		
	表示这是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件
	
(2)、@EnableConfigurationProperties(HttpEncodingProperties.class) 	
	启动指定类的ConfigurationProperties功能,将配置文件中对应的值和HttpEncodingProperties绑定起来,
	并把HttpEncodingProperties加入到ioc容器中
	
(3)、@ConditionalOnWebApplication 	
	Spring底层@Conditional注解,根据不同的条件,如果满足指定的条件,整个配置类里面的配置就会生效;
	判断当前应用是否是web应用,如果是,当前配置类生效
	
(4)、@ConditionalOnClass(CharacterEncodingFilter.class) 
	判断当前项目有没有这个类CharacterEncodingFilter;SpringMVC中进行乱码解决的过滤器;
	
(5)、@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true) 
	判断配置文件中是否存在某个配置 spring.http.encoding.enabled;如果不存在,判断也是成立的,
	即使我们配置文件中不配置pring.http.encoding.enabled=true,也是默认生效的;	

一但这个配置类生效,这个配置类就会给容器中添加各种组件,这些组件的属性是从对应的properties类(参看HttpEncodingProperties.class)中获取的,这些类里面的每一个属性又是和配置文件绑定的;

3、HttpEncodingProperties.class

所有在配置文件中能配置的属性都是在xxxxProperties类(该例子中,对应HttpEncodingProperties类)中封装着,配置文件能配置什么就可以参照某个功能对应的这个属性类;

//从配置文件中获取指定的值和bean的属性进行绑定
@ConfigurationProperties(prefix = "spring.http.encoding")
public class HttpEncodingProperties {

	public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

	private Charset charset = DEFAULT_CHARSET;

	private Boolean force;

	private Boolean forceRequest;

	private Boolean forceResponse;

	private Map<Locale, Charset> mapping;
	
	//此处略
	……
}

五、自动配置类生效

自动配置类必须在一定的条件下才能生效;

必须是@Conditional指定的条件成立,才给容器中添加组件,配置配里面的所有内容才生效;

1、@Conditional派生注解

在这里插入图片描述

六、总结

(1)、SpringBoot启动会加载大量的自动配置类;

(2)、看我们需要的功能有没有SpringBoot默认写好的自动配置类;

(3)、再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件有,我们就不需要再来配置了)

(4)、给容器中自动配置类添加组件的时候,会从properties类中获取某些属性,我们就可以在配置文件中指定这些属性的值;

(5)、规则
xxxxAutoConfigurartion:自动配置类,给容器中添加组件;
xxxxProperties:封装配置文件中相关属性;

(6)、规则SpringBoot启动流程:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

止步前行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值