Springboot 源码分析 —— prepareEnvironment() 解析

本文详细分析了Springboot启动过程中`prepareEnvironment()`方法,该方法主要负责配置文件信息的查找和设置。内容包括:1. `prepareEnvironment()`通过监听器ConfigFileApplicationListener读取和加载配置文件;2. `load()`方法为核心配置文件加载过程,涉及初始化profiles、确定搜索位置及实际加载操作。
摘要由CSDN通过智能技术生成



  • Springboot 源码分析—— 总纲 中介绍了 Springboot 启动的总过程,本文将详细解析其中的 prepareEnvironment() 方法。
  • prepareEnvironment() 方法主要是为了查找并设置配置文件信息到 environment 中。


1 prepareEnvironment():查找并设置配置文件信息

  • 根据应用类型,创建应用环境:如得到系统的参数、JVMServlet 等参数,等
  • defaultPropertiescommandLineactive-prifiles 属性加载到环境中
  • 将配置文件加载到环境中
//SpringApplication:
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments) {
   
    //根据应用类型,创建应用环境:如得到系统的参数、JVM及Servlet等参数,等
    ConfigurableEnvironment environment = this.getOrCreateEnvironment();
    //将 defaultProperties、commandLine及active-prifiles 属性加载到环境中
    //commandLine 在 args 中配置
    //其它参数可在如下4个路径中配置:servletConfigInitParams、servletContextInitParams、systemProperties、systemEnvironment
    this.configureEnvironment((ConfigurableEnvironment)environment, applicationArguments.getSourceArgs());
    //1.1 将 spirng.config 配置文件加载到环境中
    listeners.environmentPrepared((ConfigurableEnvironment)environment);
    this.bindToSpringApplication((ConfigurableEnvironment)environment);
    if (!this.isCustomEnvironment) {
   
        environment = (new EnvironmentConverter(this.getClassLoader())).convertEnvironmentIfNecessary((ConfigurableEnvironment)environment, this.deduceEnvironmentClass());
    }
	//加一个ConfigurationPropertySources
    ConfigurationPropertySources.attach((Environment)environment);
    return (ConfigurableEnvironment)environment;
}

1.1 environmentPrepared():运行一些7个监听器,主要是ConfigFileApplicationListener

  • 运行7监听器中的环境配置类,关键的是 ConfigFileApplicationListener,来读取配置文件,其它六个为:
  • AnsiOutputApplicationListener:不知道干啥
  • LoggingApplicationListener:不知道干啥
  • ClasspathLoggingApplicationListener:打日志
  • BackgroundPreinitializer:不知道干啥
  • DelegatingApplicationListener:不知道干啥
  • FileEncodingApplicationListener:判断编解码是否强制
//SpringApplicationRunListeners:
//这里之后,environment中的PropertySources中已经包含了所有的配置文件了
//这里的listeners就一个:EventPublishingRunListener
public void environmentPrepared(ConfigurableEnvironment environment) {
   
    Iterator var2 = this.listeners.iterator();

    while(var2.hasNext()) {
   
        SpringApplicationRunListener listener = (SpringApplicationRunListener)var2.next();
        listener.environmentPrepared
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值