我们假如有了自己的ApplicationContextInitializer实现类,我们在resource下面新建/META-INF/spring.factories文件,按上面的格式写上就可以被加载了
org.springframework.context.ApplicationContextInitializer=\ org.my.zb.MyApplicationContextInitializer我们把思维拉回去,讲完了怎么取的实现类名称集合
回去看 createSpringFactoriesInstances();
private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, ClassLoader classLoader, Object[] args, Set<String> names) { List<T> instances = new ArrayList<>(names.size()); for (String name : names) { try { Class<?> instanceClass = ClassUtils.forName(name, classLoader); Assert.isAssignable(type, instanceClass); Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes); T instance = (T) BeanUtils.instantiateClass(constructor, args); instances.add(instance); } catch (Throwable ex) { throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, ex); } } return instances; }(1) 获取Class
(2) 获取构造函数
(3) 利用反射新建instance对象
(4) 加入集合
至此,我们就得到了:List instances
2、执行ApplicationContextInitializer我们看SpringApplication的run方法:
public ConfigurableApplicationContext run(String... args) { ... try { ... prepareContext(context, environment, listeners, applicationArguments, printedBanner); ... } catch (Throwable ex) { ... } ... return context; }进入到prepareContext方法:
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment, SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) { ... applyInitializers(context); ... }