代碼分析版本為2.1.4.RELEASE
springboot是spring的拓展框架,不需要再寫xml文件,來配置bean的加載丰歌,使開發(fā)更加便捷和高效姨蟋。
1. 從哪里加載bean?
從注解開始分析
SpringBootApplication.java:
@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 { …… }
分別查看SpringBootApplication上的注解立帖,發(fā)現(xiàn)EnableAutoConfiguration.java有比較重要的信息:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
//重點看這里
@AutoConfigurationPackage
//重點看這里
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
/**
* Exclude specific auto-configuration classes such that they will never be applied.
* @return the classes to exclude
*/
Class<?>[] exclude() default {};
/**
* Exclude specific auto-configuration class names such that they will never be
* applied.
* @return the class names to exclude
* @since 1.3.0
*/
String[] excludeName() default {};
}
@AutoConfigurationPackage:表示將該類所對應(yīng)的包加入到自動配置眼溶。即將MainApplication.java對應(yīng)的包名加入到自動裝配。@Import(AutoConfigurationImportSelector.class) :這里在程序初始化的時候晓勇,會執(zhí)行AutoConfigurationImportSelector.AutoConfigurationGroup.process堂飞,自動裝載bean,詳情邏輯請繼續(xù)看下面绑咱。
AutoConfigurationImportSelector.java:
public class AutoConfigurationImportSelector
implements DeferredImportSelector, BeanClassLoaderAware, ResourceLoaderAware,
BeanFactoryAware, EnvironmentAware, Ordered {
}
AutoConfigurationImportSelector的類圖:
可見其實現(xiàn)了DeferredImportSelector類绰筛,而DeferredImportSelector又繼承ImportSelector類。該實現(xiàn)關(guān)系請記住描融,將有利于下面的代碼分析铝噩。
在這里,先跟大家說一下稼稿,程序初始化的時候會執(zhí)行AutoConfigurationImportSelector.AutoConfigurationGroup.process(為什么會執(zhí)行該方法薄榛?詳情查看2)
那么該方法實現(xiàn)了什么邏輯呢讳窟?
@Override
public void process(AnnotationMetadata annotationMetadata,
DeferredImportSelector deferredImportSelector) {
Assert.state(
deferredImportSelector instanceof AutoConfigurationImportSelector,
() -> String.format("Only %s implementations are supported, got %s",
AutoConfigurationImportSelector.class.getSimpleName(),
deferredImportSelector.getClass().getName()));
//重點看這里:獲取自動裝配實體
AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector)
.getAutoConfigurationEntry(getAutoConfigurationMetadata(),
annotationMetadata);
this.autoConfigurationEntries.add(autoConfigurationEntry);
for (String importClassName : autoConfigurationEntry.getConfigurations()) {
this.entries.putIfAbsent(importClassName, annotationMetadata);
}
}
其中再看一下getAutoConfigurationEntry方法:
/**
* 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);
//猜測:獲取配置類让歼,從哪里獲取丽啡?再細(xì)看這里的代碼
List<String> configurations = getCandidateConfigurations(annotationMetadata,
attributes);
//刪除重復(fù)名稱的bean
configurations = removeDuplicates(configurations);
//獲取元數(shù)據(jù)的不應(yīng)包括的類名(excludeName谋右、exclude)
Set<String> exclusions = getExclusions(annotationMetadata, attributes);
checkExcludedClasses(configurations, exclusions);
//刪除不應(yīng)包括的類名
configurations.removeAll(exclusions);
//過濾需要過濾的配置類
configurations = filter(configurations, autoConfigurationMetadata);
fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationEntry(configurations, exclusions);
}
下面來重點看看該方法的實現(xiàn):
//猜測:獲取配置類,從哪里獲炔构俊改执?再細(xì)看這里的代碼
List<String> configurations = getCandidateConfigurations(annotationMetadata,
attributes);
org.springframework.boot.autoconfigure.AutoConfigurationImportSelector#getCandidateConfigurations:
/**
* Return the auto-configuration class names that should be considered. By default
* this method will load candidates using {@link SpringFactoriesLoader} with
* {@link #getSpringFactoriesLoaderFactoryClass()}.
* @param metadata the source metadata
* @param attributes the {@link #getAttributes(AnnotationMetadata) annotation
* attributes}
* @return a list of candidate configurations
*/
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
AnnotationAttributes attributes) {
//實質(zhì)調(diào)用了SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class, this.beanClassLoader);
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
Assert.notEmpty(configurations,
"No auto configuration classes found in META-INF/spring.factories. If you "
+ "are using a custom packaging, make sure that file is correct.");
return configurations;
}
/**
* Return the class used by {@link SpringFactoriesLoader} to load configuration
* candidates.
* @return the factory class
*/
protected Class<?> getSpringFactoriesLoaderFactoryClass() {
return EnableAutoConfiguration.class;
}
從上面的代碼注解中,繼續(xù)深入loadFactoryNames方法,即獲取EnableAutoConfiguration為key的所有類名
org.springframework.core.io.support.SpringFactoriesLoader#loadFactoryNames:
public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
String factoryClassName = factoryClass.getName();
return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}
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 ?
//注解1:FACTORIES_RESOURCE_LOCATION=META-INF/spring.factories,即從該路徑下獲取類
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()) {
String factoryClassName = ((String) entry.getKey()).trim();
for (String factoryName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
result.add(factoryClassName, factoryName.trim());
}
}
}
cache.put(classLoader, result);
return result;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load factories from location [" +
FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
注解1:就是加載所有包的spring.factories文件坑雅,然后逐個解釋
其中:
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
解釋spring.factories文件
如下圖所示辈挂,某個包下的spring.factories文件:
轉(zhuǎn)化為
org.springframework.boot.autoconfigure.EnableAutoConfiguration->
org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration
相關(guān)流程圖如下:
2. 為什么會執(zhí)行AutoConfigurationImportSelector.AutoConfigurationGroup.process?
從springApplication.run開始:
代碼太多裹粤,挑重點的說:
org.springframework.context.annotation.ConfigurationClassParser#doProcessConfigurationClass
會處理如下圖所示的注解终蒂,在分析@Import注解時,會查看該類是不是實現(xiàn)DeferredImportSelector類遥诉,如果是拇泣,則會調(diào)用this.deferredImportSelectorHandler.process()。很明顯矮锈,在前面提到霉翔,AutoConfigurationImportSelector實現(xiàn)了DeferredImportSelector,所以在后面的邏輯中苞笨,會調(diào)用AutoConfigurationImportSelector.AutoConfigurationGroup.process方法
總結(jié):
- springboot會自動掃描mainApplication類所在包的所有bean
- springboot會自動掃描jar包下面的/META-INF/spring.factories文件债朵,將EnableAutoConfiguration為key的所有類名加載出來子眶,并進(jìn)行去重、過濾