ApplicationContextInitializer 主要用在容器刷新之前调用改接口实现类的 initialize 方法,并将 ConfigurableApplicationContext 类的实例作为参数传入。通常用于根据应用上下文进行处理的编程中。且实现类可以通过 Ordered 接口或 @Order 注解 进行多个 Initializer 的排序。
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return new SpringApplication(primarySources).run(args);
}
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
...
//初始化ApplicationContextInitializer
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
//初始化应用监听器
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
}
public void setInitializers(Collection<? extends ApplicationContextInitializer<?>> initializers) {
this.initializers = new ArrayList<>();
this.initializers.addAll(initializers);
}
1、SPI加载spring.factories文件
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
ClassLoader classLoader = getClassLoader();
Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
//通过类的全限定名反射实例化全部子类
List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
通过指定的类名类型type从spring.factories文件中获取对应的子类全限定类名集合。通过反射方式实例化对应的全部子类。
1.1、SpringFactoriesLoader
public final class SpringFactoriesLoader {
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
private static final Map<ClassLoader, MultiValueMap<String, String>> cache = new ConcurrentReferenceHashMap<>();
public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
String factoryClassName = factoryClass.getName();
// 从MultiValueMap获取 org.springframework.context.ApplicationContextInitializer类型的子类
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;
}
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()) {
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;
}
}
- 通过类加载器获取类路径下存在的spring.factories文件。加载内部预先定义的类文件。
- cache缓存预先解析完成的所有预加载类信息。
核心spring-boot.jar、spring-beans.jar包下的spring.factories文件。
spring-boot.jar#spring.factories部分内容如下:
# Application Context Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\
org.springframework.boot.context.ContextIdApplicationContextInitializer,\
org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\
org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer
# Run Listeners
org.springframework.boot.SpringApplicationRunListener=\
org.springframework.boot.context.event.EventPublishingRunListener
# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.ConfigFileApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener
针对上述配置类信息,MultiValueMap中key为全限定接口名,其对应的value为对应全部子类的全限定类名的List集合。
2、示例
@Slf4j
public class CustomApplicationContextInitializer implements ApplicationContextInitializer {
@Override//AnnotationConfigServletWebServerApplicationContext
public void initialize(ConfigurableApplicationContext applicationContext) {
log.error("========== this is custom applicationContextInitializer ===============");
}
}
三种将自定义ApplicationContextInitializer添加到SpringApplication。
2.1、方式一
SpringApplication springApplication = new SpringApplication(BootApp.class);
springApplication.addInitializers(new CustomApplicationContextInitializer());
ConfigurableApplicationContext run = springApplication.run(args);
2.2、方式二
SPI 扩展 META-INF/spring.factories:
org.springframework.context.ApplicationContextInitializer=\
boot.initializer.Custom3ApplicationContextInitializer
2.3、方式三
在配置文件 application.properties 中添加如下配置:
context.initializer.classes = boot.initializer.Custom2ApplicationContextInitializer