springboot在prepareEnvironment函数中环境转换的问题

GuDongYu1 GuDongYu1 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
我在看springboot的源码,不太懂prepareEnvironment函数中为什么要有这个if代码块。

if的条件中是判断是否为自定义环境,如果是自定义环境那么就不会执行if代码块,如果是通过getOrCreateEnvironment创建的环境,说明不是自定义环境,那会进入if代码块执行。

进入if代码块后,会对环境进行转换,看convertEnvironmentfINecessary函数,最开始的类型判断应该一定会返回true的呀,在其他地方也没发现谁调用过convertEnvironmentIfNecessary这个函数,说明convertEnvironmentIfNecessary函数中的第二个return不会被执行。

那这么写的作用是什么,感谢各位大佬指导下。


private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
DefaultBootstrapContext bootstrapContext, ApplicationArguments applicationArguments) {
ConfigurableEnvironment environment = getOrCreateEnvironment();
configureEnvironment(environment, applicationArguments.getSourceArgs());
ConfigurationPropertySources.attach(environment);
listeners.environmentPrepared(bootstrapContext, environment);
DefaultPropertiesPropertySource.moveToEnd(environment);
configureAdditionalProfiles(environment);
bindToSpringApplication(environment);
if (!this.isCustomEnvironment) {
environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,
deduceEnvironmentClass());
}
ConfigurationPropertySources.attach(environment);
return environment;
}

StandardEnvironment convertEnvironmentIfNecessary(ConfigurableEnvironment environment,
Class<? extends StandardEnvironment> type) {
if (type.equals(environment.getClass())) {
return (StandardEnvironment) environment;
}
return convertEnvironment(environment, type);
}

private ConfigurableEnvironment getOrCreateEnvironment() {
if (this.environment != null) {
return this.environment;
}
switch (this.webApplicationType) {
case SERVLET:
return new StandardServletEnvironment();
case REACTIVE:
return new StandardReactiveWebEnvironment();
default:
return new StandardEnvironment();
}
}

private Class<? extends StandardEnvironment> deduceEnvironmentClass() {
switch (this.webApplicationType) {
case SERVLET:
return StandardServletEnvironment.class;
case REACTIVE:
return StandardReactiveWebEnvironment.class;
default:
return StandardEnvironment.class;
}
}

...全文
评论 1
收藏 已收藏
分享
返回顶部
GuDongYu1
Java EE 67,535 成员 225,843 内容