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

GuDongYu1 2021-05-14 11:18:17
我在看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;
}
}

...全文
114 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
KeepSayingNo 2021-05-14
  • 打赏
  • 举报
回复
做环境预处理是因为springboot支持不同的启动方式,它必须要清楚当前是什么环境才能决定以哪种方式启动,不想spring mvc,你的web server是外部的

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧