1、流程概述
1、从classpath下的 META-INF/spring.factories(点击查看)文件中找出 ApplicationListener
类型的所有类的全类名。
2、通过反射创建这些类的对象
3、最后把这些对象放入SpringApplication对象的List实例变量中。
示意图 |
---|
![]() |
2、状态图
此时 SpringApplication 对象的内存状态如下图
SpringApplication 内存状态 |
---|
![]() |
3、源码解读
2.1、源码结构
![]() |
源码结构:
initialize
|- getSpringFactoriesInstances
|- SpringFactoriesLoader.loadFactoryNames
|- createSpringFactoriesInstances
|- AnnotationAwareOrderComparator.sort
|- setListeners
2.2、参考源码
private void initialize(Object[] sources) {
if (sources != null && sources.length > 0) {
this.sources.addAll(Arrays.asList(sources));
}
this.webEnvironment = deduceWebEnvironment();
setInitializers((Collection) getSpringFactoriesInstances(
ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
本文关注的是这行代码:setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class))
private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type) {
return getSpringFactoriesInstances(type, new Class<?>[] {});
}
private <T> Collection<? extends T> getSpringFactoriesInstances(Class<T> type,
Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Use names and ensure unique to protect against duplicates
Set<String> names = new LinkedHashSet<String>(
SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
private List<ApplicationListener<?>> listeners;
public void setListeners(Collection<? extends ApplicationListener<?>> listeners) {
this.listeners = new ArrayList<ApplicationListener<?>>();
this.listeners.addAll(listeners);
}
getSpringFactoriesInstances方法用来解析并创建 ApplicationListener 实例
其中 getSpringFactoriesInstances(ApplicationListener.class)
如下:
names = {LinkedHashSet@1636} size = 10
0 = "o.s.boot.ClearCachesApplicationListener"
1 = "o.s.boot.builder.ParentContextCloserApplicationListener"
2 = "o.s.boot.context.FileEncodingApplicationListener"
3 = "o.s.boot.context.config.AnsiOutputApplicationListener"
4 = "o.s.boot.context.config.ConfigFileApplicationListener"
5 = "o.s.boot.context.config.DelegatingApplicationListener"
6 = "o.s.boot.liquibase.LiquibaseServiceLocatorApplicationListener"
7 = "o.s.boot.logging.ClasspathLoggingApplicationListener"
8 = "o.s.boot.logging.LoggingApplicationListener"
9 = "o.s.boot.autoconfigure.BackgroundPreinitializer"
setListeners方法这些实例放入SpringApplication 实例的 List<ApplicationListener<?>> listeners
变量中。