示例位置 SpringApplication#getSpringFactoriesInstances
加载spring.factroies下的初始化类
ClassLoader classLoader = this.getClassLoader();
Set names = new LinkedHashSet(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
List instances = this.createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
AnnotationAwareOrderComparator.sort(instances);
return instances;
说明:
SpringFactoriesLoader.loadFactoryNames 加载type为spring.factroies 下的 class的key值
List loadFactoryNames(Class> factoryType, @Nullable ClassLoader classLoader)
示例位置 SpringApplication#createSpringFactoriesInstances
try {
Class> instanceClass = ClassUtils.forName(name, classLoader);
Assert.isAssignable(type, instanceClass);
Constructor> constructor = instanceClass.getDeclaredConstructor(parameterTypes);
T instance = BeanUtils.instantiateClass(constructor, args);
instances.add(instance);
} catch (Throwable var12) {
throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, var12);
}
ClassUtils.forName,name为加载类的全路径名称,通过ClassUtils.forName加载对应的类
通过 instanceClass.getDeclaredConstructor(parameterTypes); 表示传入无参的构造参数
示例此处的值为:new Class[0] ,
new Class[0]表示有零个元素的Class数组,即空数组,与传入null结果是一样的,都表示取得无参构造方法。
但是使用该方式可以避免抛出空异常。
BeanUtils.instantiateClass(constructor, args); 通过构造函数,入参实例化一个对象
org.springframework.util.ClassUtils#forName
public static Class> forName(String name, @Nullable ClassLoader classLoader) throws ClassNotFoundException, LinkageError
org.springframework.beans.BeanUtils#instantiateClass
instantiateClass(Constructor ctor, Object... args)
函数参数调用方
示例位置:SpringApplicationRunListeners#starting
this.doWithListeners("spring.boot.application.starting", (listener) -> {
listener.starting(bootstrapContext);
}, (step) -> {
if (mainApplicationClass != null) {
step.tag("mainApplicationClass", mainApplicationClass.getName());
}
});
函数参数定义方
private void doWithListeners(String stepName, Consumer listenerAction, Consumer stepAction) {
StartupStep step = this.applicationStartup.start(stepName);
this.listeners.forEach(listenerAction);
if (stepAction != null) {
stepAction.accept(step);
}
step.end();
}
}