运行SpringApplication三

本文详细解析了Spring Boot应用中环境后置处理器的应用过程,包括`EnvironmentPostProcessorApplicationListener`的事件处理流程,从`EnvironmentPostProcessor`的获取、工厂初始化到实例化。重点展示了如何通过`SpringFactories`加载后置处理器,并按类型排序执行它们的环境配置.

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前面我们看到创建了6个监听器,下面逐一查看

首先是org.springframework.boot.env.EnvironmentPostProcessorApplicationListener

———— onApplicationEvent start

org.springframework.boot.env.EnvironmentPostProcessorApplicationListener

@Override
public void onApplicationEvent(ApplicationEvent event) {
	if (event instanceof ApplicationEnvironmentPreparedEvent) {
		onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event);
	}
	if (event instanceof ApplicationPreparedEvent) {
		onApplicationPreparedEvent();
	}
	if (event instanceof ApplicationFailedEvent) {
		onApplicationFailedEvent();
	}
}

————— onApplicationEnvironmentPreparedEvent start

org.springframework.boot.env.EnvironmentPostProcessorApplicationListener

private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) {
	ConfigurableEnvironment environment = event.getEnvironment();
	SpringApplication application = event.getSpringApplication();
	for (EnvironmentPostProcessor postProcessor : getEnvironmentPostProcessors(application.getResourceLoader(),
			event.getBootstrapContext())) {
		postProcessor.postProcessEnvironment(environment, application);
	}
}
获取后置处理器
getEnvironmentPostProcessors(application.getResourceLoader(), event.getBootstrapContext())

—————— getEnvironmentPostProcessors start

org.springframework.boot.env.EnvironmentPostProcessorApplicationListener

private final Function<ClassLoader, EnvironmentPostProcessorsFactory> postProcessorsFactory;

List<EnvironmentPostProcessor> getEnvironmentPostProcessors(ResourceLoader resourceLoader,
		ConfigurableBootstrapContext bootstrapContext) {
	ClassLoader classLoader = (resourceLoader != null) ? resourceLoader.getClassLoader() : null;
	EnvironmentPostProcessorsFactory postProcessorsFactory = this.postProcessorsFactory.apply(classLoader);
	return postProcessorsFactory.getEnvironmentPostProcessors(this.deferredLogs, bootstrapContext);
}
获取环境后置处理器工厂
EnvironmentPostProcessorsFactory postProcessorsFactory = this.postProcessorsFactory.apply(classLoader);

postProcessorsFactory于构造方法内初始化,由之前的学习得知监听器均由无参构造方法创建

查看构造方法

——————— EnvironmentPostProcessorApplicationListener start

org.springframework.boot.env.EnvironmentPostProcessorApplicationListener

private final DeferredLogs deferredLogs;

private final Function<ClassLoader, EnvironmentPostProcessorsFactory> postProcessorsFactory;

public EnvironmentPostProcessorApplicationListener() {
	this((classLoader) -> EnvironmentPostProcessorsFactory.fromSpringFactories(classLoader), new DeferredLogs());
}

EnvironmentPostProcessorApplicationListener(
		Function<ClassLoader, EnvironmentPostProcessorsFactory> postProcessorsFactory, DeferredLogs deferredLogs) {
	this.postProcessorsFactory = postProcessorsFactory;
	this.deferredLogs = deferredLogs;
}
执行apply方法

即前面的(classLoader) -> EnvironmentPostProcessorsFactory.fromSpringFactories(classLoader)
———————— fromSpringFactories start

org.springframework.boot.env.EnvironmentPostProcessorsFactory

static EnvironmentPostProcessorsFactory fromSpringFactories(ClassLoader classLoader) {
	return new ReflectionEnvironmentPostProcessorsFactory(classLoader,
			SpringFactoriesLoader.loadFactoryNames(EnvironmentPostProcessor.class, classLoader));
}
创建反射后置处理器工厂实例并返回

————————— ReflectionEnvironmentPostProcessorsFactory start

org.springframework.boot.env.ReflectionEnvironmentPostProcessorsFactory

private final List<Class<?>> classes;

private ClassLoader classLoader;

private final List<String> classNames;

ReflectionEnvironmentPostProcessorsFactory(ClassLoader classLoader, List<String> classNames) {
	this.classes = null;
	this.classLoader = classLoader;
	this.classNames = classNames;
}

————————— ReflectionEnvironmentPostProcessorsFactory end
根据org.springframework.boot.env.EnvironmentPostProcessor共读取到7个类名
org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor
org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor
org.springframework.boot.env.RandomValuePropertySourceEnvironmentPostProcessor
org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor
org.springframework.boot.env.SystemEnvironmentPropertySourceEnvironmentPostProcessor
org.springframework.boot.reactor.DebugAgentEnvironmentPostProcessor
org.springframework.boot.autoconfigure.integration.IntegrationPropertiesEnvironmentPostProcessor
———————— fromSpringFactories end
——————— EnvironmentPostProcessorApplicationListener end

获取环境后置处理器集合并返回
return postProcessorsFactory.getEnvironmentPostProcessors(this.deferredLogs, bootstrapContext);

——————— getEnvironmentPostProcessors start

org.springframework.boot.env.ReflectionEnvironmentPostProcessorsFactory

@Override
public List<EnvironmentPostProcessor> getEnvironmentPostProcessors(DeferredLogFactory logFactory,
		ConfigurableBootstrapContext bootstrapContext) {
	Instantiator<EnvironmentPostProcessor> instantiator = new Instantiator<>(EnvironmentPostProcessor.class,
			(parameters) -> {
				parameters.add(DeferredLogFactory.class, logFactory);
				parameters.add(Log.class, logFactory::getLog);
				parameters.add(ConfigurableBootstrapContext.class, bootstrapContext);
				parameters.add(BootstrapContext.class, bootstrapContext);
				parameters.add(BootstrapRegistry.class, bootstrapContext);
			});
	return (this.classes != null) ? instantiator.instantiateTypes(this.classes)
			: instantiator.instantiate(this.classLoader, this.classNames);
}
创建实例化器
Instantiator<EnvironmentPostProcessor> instantiator = new Instantiator<>(EnvironmentPostProcessor.class,
		(parameters) -> {
			parameters.add(DeferredLogFactory.class, logFactory);
			parameters.add(Log.class, logFactory::getLog);
			parameters.add(ConfigurableBootstrapContext.class, bootstrapContext);
			parameters.add(BootstrapContext.class, bootstrapContext);
			parameters.add(BootstrapRegistry.class, bootstrapContext);
		});

———————— Instantiator start

org.springframework.boot.util.Instantiator

private final Class<?> type;

private final Map<Class<?>, Function<Class<?>, Object>> availableParameters;

public Instantiator(Class<?> type, Consumer<AvailableParameters> availableParameters) {
	this.type = type;
	this.availableParameters = getAvailableParameters(availableParameters);
}

————————— getAvailableParameters start

org.springframework.boot.util.Instantiator

private Map<Class<?>, Function<Class<?>, Object>> getAvailableParameters(
		Consumer<AvailableParameters> availableParameters) {
	Map<Class<?>, Function<Class<?>, Object>> result = new LinkedHashMap<>();
	availableParameters.accept(new AvailableParameters() {

		@Override
		public void add(Class<?> type, Object instance) {
			result.put(type, (factoryType) -> instance);
		}

		@Override
		public void add(Class<?> type, Function<Class<?>, Object> factory) {
			result.put(type, factory);
		}

	});
	return Collections.unmodifiableMap(result);
}
创建集合实例
Map<Class<?>, Function<Class<?>, Object>> result = new LinkedHashMap<>();
创建可用参数集合实例作为参数,供availableParameters使用
availableParameters.accept(new AvailableParameters() {

	@Override
	public void add(Class<?> type, Object instance) {
		result.put(type, (factoryType) -> instance);
	}

	@Override
	public void add(Class<?> type, Function<Class<?>, Object> factory) {
		result.put(type, factory);
	}

});

org.springframework.boot.util.Instantiator$AvailableParameters匿名实例实现add方法,将参数对象保存至result集合
accept方法即上文lambd

(parameters) -> {
	parameters.add(DeferredLogFactory.class, logFactory);
	parameters.add(Log.class, logFactory::getLog);
	parameters.add(ConfigurableBootstrapContext.class, bootstrapContext);
	parameters.add(BootstrapContext.class, bootstrapContext);
	parameters.add(BootstrapRegistry.class, bootstrapContext);
}

添加5项可用参数至result

根据result创建不可变更集合并返回
return Collections.unmodifiableMap(result);

————————— getAvailableParameters end
———————— Instantiator end

获取环境后置处理器集合并返回
return (this.classes != null) ? instantiator.instantiateTypes(this.classes)
		: instantiator.instantiate(this.classLoader, this.classNames);

此时classesnull,以名称获取

instantiator.instantiate(this.classLoader, this.classNames)

———————— instantiate start

org.springframework.boot.util.Instantiator

public List<T> instantiate(ClassLoader classLoader, Collection<String> names) {
	Assert.notNull(names, "Names must not be null");
	return instantiate(names.stream().map((name) -> TypeSupplier.forName(classLoader, name)));
}
创建 org.springframework.boot.util.Instantiator$TypeSupplier
names.stream().map((name) -> TypeSupplier.forName(classLoader, name))

————————— forName start

org.springframework.boot.util.Instantiator$TypeSupplier

static TypeSupplier forName(ClassLoader classLoader, String name) {
	return new TypeSupplier() {

		@Override
		public String getName() {
			return name;
		}

		@Override
		public Class<?> get() throws ClassNotFoundException {
			return ClassUtils.forName(name, classLoader);
		}

	};
}

用于根据名称获取类实例
————————— forName end

调用 instantiate方法获取实例集合

————————— instantiate start

org.springframework.boot.util.Instantiator

private List<T> instantiate(Stream<TypeSupplier> typeSuppliers) {
	List<T> instances = typeSuppliers.map(this::instantiate).collect(Collectors.toList());
	AnnotationAwareOrderComparator.sort(instances);
	return Collections.unmodifiableList(instances);
}
将流转换为实例集合
List<T> instances = typeSuppliers.map(this::instantiate).collect(Collectors.toList());

—————————— instantiate start

org.springframework.boot.util.Instantiator

private T instantiate(TypeSupplier typeSupplier) {
	try {
		Class<?> type = typeSupplier.get();
		Assert.isAssignable(this.type, type);
		return instantiate(type);
	}
	catch (Throwable ex) {
		throw new IllegalArgumentException(
				"Unable to instantiate " + this.type.getName() + " [" + typeSupplier.getName() + "]", ex);
	}
}
获取类型
Class<?> type = typeSupplier.get();
判断类型是否为指定类型或其子类
Assert.isAssignable(this.type, type);
返回实例集合
return instantiate(type);

——————————— instantiate start

org.springframework.boot.util.Instantiator

private static final Comparator<Constructor<?>> CONSTRUCTOR_COMPARATOR = Comparator
		.<Constructor<?>>comparingInt(Constructor::getParameterCount).reversed();

@SuppressWarnings("unchecked")
private T instantiate(Class<?> type) throws Exception {
	Constructor<?>[] constructors = type.getDeclaredConstructors();
	Arrays.sort(constructors, CONSTRUCTOR_COMPARATOR);
	for (Constructor<?> constructor : constructors) {
		Object[] args = getArgs(constructor.getParameterTypes());
		if (args != null) {
			ReflectionUtils.makeAccessible(constructor);
			return (T) constructor.newInstance(args);
		}
	}
	throw new IllegalAccessException("Unable to find suitable constructor");
}
获取构造器集合
Constructor<?>[] constructors = type.getDeclaredConstructors();
对构造器集合进行排序
Arrays.sort(constructors, CONSTRUCTOR_COMPARATOR);

根据参数数量反向排序

遍历集合
for (Constructor<?> constructor : constructors)

———————————— for start

获取参数数组
Object[] args = getArgs(constructor.getParameterTypes());

————————————— getArgs start

org.springframework.boot.util.Instantiator

private Object[] getArgs(Class<?>[] parameterTypes) {
	Object[] args = new Object[parameterTypes.length];
	for (int i = 0; i < parameterTypes.length; i++) {
		Function<Class<?>, Object> parameter = getAvailableParameter(parameterTypes[i]);
		if (parameter == null) {
			return null;
		}
		args[i] = parameter.apply(this.type);
	}
	return args;
}
创建参数数组
Object[] args = new Object[parameterTypes.length];
遍历参数类型
for (int i = 0; i < parameterTypes.length; i++)

——————————————— for start

获取可用参数
Function<Class<?>, Object> parameter = getAvailableParameter(parameterTypes[i]);

——————————————— getAvailableParameter start

org.springframework.boot.util.Instantiator

private Function<Class<?>, Object> getAvailableParameter(Class<?> parameterType) {
	for (Map.Entry<Class<?>, Function<Class<?>, Object>> entry : this.availableParameters.entrySet()) {
		if (entry.getKey().isAssignableFrom(parameterType)) {
			return entry.getValue();
		}
	}
	return null;
}

遍历之前创建的参数集合实例availableParameters,返回类型匹配的参数
——————————————— getAvailableParameter end

判断参数
if (parameter == null) {
	return null;
}
参数数组赋值
args[i] = parameter.apply(this.type);

——————————————— for end

返回参数数组
return args;

————————————— getArgs end

使构造器可用
ReflectionUtils.makeAccessible(constructor);
使用构造器实例化并返回
return (T) constructor.newInstance(args);

———————————— for end
——————————— instantiate end
—————————— instantiate end

将实例集合排序
AnnotationAwareOrderComparator.sort(instances);
创建不可变更实例集合并返回
return Collections.unmodifiableList(instances);

————————— instantiate end
———————— instantiate end
——————— getEnvironmentPostProcessors end
—————— getEnvironmentPostProcessors end
现已得到7个后置处理器实例,顺序如下
org.springframework.boot.env.RandomValuePropertySourceEnvironmentPostProcessor
org.springframework.boot.env.SystemEnvironmentPropertySourceEnvironmentPostProcessor
org.springframework.boot.env.SpringApplicationJsonEnvironmentPostProcessor
org.springframework.boot.cloud.CloudFoundryVcapEnvironmentPostProcessor
org.springframework.boot.context.config.ConfigDataEnvironmentPostProcessor
org.springframework.boot.reactor.DebugAgentEnvironmentPostProcessor
org.springframework.boot.autoconfigure.integration.IntegrationPropertiesEnvironmentPostProcessor

遍历后置处理器集合,进行处理
postProcessor.postProcessEnvironment(environment, application);

————— onApplicationEnvironmentPreparedEvent end
———— onApplicationEvent end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值