将启动类作为切入点,启动类的代码如下
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
这个类的被@SpringBootApplication所修饰,我们就将该注释作为切入点,分析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) })
该组合注解包含了@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan三个注解(这三个注解足够去了解自动配置过程),在这三个注解中@EnableAutoConfiguration是我们最为关注的重点。从他的名字也可以看出他与自动配置有关,点开该注解发现他也是一个组合注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
在这些注解中包含一个@Import注解,该注解用于给容器中导入组件,该注解传入了一个AutoConfigurationImportSelector类,这应该是我们寻找的目标,查看他的源码
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());
}
该类中有一个selectImports方法主要用于返回一个包含自动配置类的数组,在这个方法中又调用了
getAutoConfigurationEntry这个方法,查看该方法
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);
}
该方法中调用了getCandidateConfigurations这个方法去获取了所有配置的类名的信息列表,而他通过调用 SpringFactoriesLoader.loadFactoryNames() ,LoadFactoryNames又调用loadSpringFactories方法来扫描加载全部META-INF/spring.factories中的jar包,该文件中记录了有哪些配置类。然后PropertiesLoaderUtils把ClassLoader扫描到的包封装成properties对象,从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他添加到容器中。
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);
if (result != null) {
return result;
} else {
try {
Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
LinkedMultiValueMap result = new LinkedMultiValueMap();
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[] var9 = StringUtils.commaDelimitedListToStringArray((String)entry.getValue());
int var10 = var9.length;
for(int var11 = 0; var11 < var10; ++var11) {
String factoryImplementationName = var9[var11];
result.add(factoryTypeName, factoryImplementationName.trim());
}
}
}
cache.put(classLoader, result);
return result;
} catch (IOException var13) {
throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var13);
}
}
}
总结一下@EnableAutoConfiguration这个注解通过扫描所有jar包之中的spring.factories封装成properties,然后根据 EnableAutoConfiguration.class 类获取对应的值,根据值加载对应的自动配置类,注入到容器之中。
现在我们把另外两个注解的含义补全,@SpringBootConfiguration 表明当前类是配置类,@ComponentScan 表明去扫描那些类,这两个注解结合@EnableAutoConfiguration共同完成了将配置类加载到容器的功能。
下面我们来查看一个自动配置类HttpEncodingAutoConfiguration
@Configuration(proxyBeanMethods = false)
//表明这是一个配置类
@EnableConfigurationProperties(HttpProperties.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
//判断当前容器是否是web容器
@ConditionalOnClass(CharacterEncodingFilter.class)
//判断容器中是否有CharacterEncodingFilter这个类
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)
//判断自定义配置中是否存在spring.http.encoding的配置,如果不存在默认为开启
public class HttpEncodingAutoConfiguration {
//和对应的配置文件建立关系
private final HttpProperties.Encoding properties;
public HttpEncodingAutoConfiguration(HttpProperties properties) {
this.properties = properties.getEncoding();
}
@Bean
@ConditionalOnMissingBean
//该类的某些值需要从上文定义的properties中获取
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;
}
.......
}
查看HttpProperties这个类中的属性即为用户可以自定义配置的属性,而这些属性的默认值记录在该jar包下面的/META-INF/里面的spring-configuration-metadata.json或者additional-spring-configuration-metadata.json中,下图是spring-configuration-metadata.json中关于字符集的设定,可以知道默认值为UTF-8
{
"name": "spring.http.encoding.charset",
"type": "java.nio.charset.Charset",
"description": "Charset of HTTP requests and responses. Added to the \"Content-Type\" header if not set explicitly.",
"sourceType": "org.springframework.boot.autoconfigure.http.HttpProperties$Encoding",
"defaultValue": "UTF-8"
},
当然更为简单的方法就是在application.properties或application.yml中使用代码提示来查看默认值了