前言
最近因为要面试,复习一下Spring,顺便做一下总结。 Spring Boot相对Spring来说,最大的特点之一便是配置类的自动装配了。它让我们抛开配置加载的细节,专注于配置的内容。做到了开箱即用。
加载过程
1. 加载配置类全限定名
SpringBootApplication 引入EnableAutoConfiguration
EnableAutoConfiguration 通过Import 引入AutoConfigurationImportSelector
AutoConfigurationImportSelector #getCandidateConfigurations 会去调用SpringFactoriesLoader.*loadFactoryNames* 来获取第三方的自配装配文件spring.factories里指定的自动配置类全限定名。以及spring-boot-starter-autoconfigure 下的META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 文件里指定的自动配置类的全限定名。
核心代码如下:
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = new ArrayList<>(
SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, getBeanClassLoader()));
ImportCandidates.load(AutoConfiguration.class, getBeanClassLoader()).forEach(configurations::add);
return configurations;
}
SpringFactoriesLoader.loadFactoryNames
static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
Enumeration<URL> urls = classLoader.getResources(FACTORIES_RESOURCE_LOCATION);
result.add(...)
return result;
}
private static final String LOCATION = "META-INF/spring/%s.imports";
public static ImportCandidates load(Class<?> annotation, ClassLoader classLoader) {
String location = String.format(LOCATION, annotation.getName());
Enumeration<URL> urls = findUrlsInClasspath(classLoaderToUse, location);
List<String> autoConfigurations = new ArrayList<>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
autoConfigurations.addAll(readAutoConfigurations(url));
}
return new ImportCandidates(autoConfigurations);
}
2. 通过配置类的全限定名注册BeanDefinition到Spring容器中
第一步跟第二步都是在ConfigurationClassPostProcessor#**processConfigBeanDefinitions 中处理的,如下:
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
ConfigurationClassParser parser = new ConfigurationClassParser(...);
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(...);
parser.parse(candidates);
Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
this.reader.loadBeanDefinitions(configClasses);
}
步骤如下:
ConfigurationClassPostProcessor # **processConfigBeanDefinitions**
→ConfigurationClassBeanDefinitionReader #registerBeanDefinitionForImportedConfigurationClass
→DefaultListableBeanFactory # registerBeanDefinition
最终是将类名加载为BeanDefinition 放到DefaultListableBeanFactory # beanDefinitionMap 中,在后面的启动过程中,容器会从这里面把BeanDefinition 拿出来去创建Bean实例。
3. 将BeanDefinition加载为SpringBean注册到Spring IOC容器
DefaultListableBeanFactory # preInstantiateSingletons ,这里负责把DefaultListableBeanFactory # beanDefinitionMap 中的BeanDefinition 拿出来创建Bean实例
与SpringContext Refresh对应
第一步跟第二步是在AbstractApplicationContext # refresh
invokeBeanFactoryPostProcessors(beanFactory);
第三步
finishBeanFactoryInitialization(beanFactory);
|