SpringBoot之application.properties的加载

本文深入探讨SpringBoot中application.properties的加载和使用。从源码角度解析,当SpringBoot启动时,配置文件在environment中加载,ConfigFileApplicationListener监听器负责加载配置。加载过程包括判断profile、加载不同环境的配置文件,特别是application.properties。配置文件的优先级由高到低依次是系统变量、环境变量、profile指定配置和默认的application.properties。在实际应用中,如DataSource的自动配置,会从propertySource中读取配置属性来生成数据源。
摘要由CSDN通过智能技术生成

SpringBoot中唯一的配置文件就是application.properties了,那这个配置文件是在什么时候被加载的,存储在什么地方,又是如何被使用的呢?下面从源码的角度来分析

1、application.properties的加载

springboot加载的配置文件是放在environment中的,在prepareEnvironment的时候,springboot读取和加载了application.properties文件
environment的详细解析见https://blog.csdn.net/woshilijiuyi/article/details/82720478

在这里插入图片描述
跟进prepareEnvironment方法

private ConfigurableEnvironment prepareEnvironment(
      SpringApplicationRunListeners listeners,
      ApplicationArguments applicationArguments) {
   //1、初始化environment
    ConfigurableEnvironment environment = getOrCreateEnvironment();
    //2、加载默认配置
    configureEnvironment(environment, applicationArguments.getSourceArgs());
    //3、通知环境监听器,加载项目中的配置文件
   listeners.environmentPrepared(environment);
   if (!this.webEnvironment) {
      environment = new EnvironmentConverter(getClassLoader())
            .convertToStandardEnvironmentIfNecessary(environment);
   }
   return environment;
}

这里主要分析listeners.environmentPrepared(environment)方法中,监听器是如何加载配置文件的

public void environmentPrepared(ConfigurableEnvironment environment) {
    //new了一个environmentPrepared的事件
   this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent(
         this.application, this.args, environment));
}
//这里就很眼熟了,这就是上一章监听器的工作原理
public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
   ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
   for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
      Executor executor = getTaskExecutor();
      if (executor != null) {
         executor.execute(new Runnable() {
    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值