SpringBoot配置文件的优先级

本文围绕SpringBoot配置文件展开,介绍了项目结构,阐述了application.properties和application.yml文件的优先级顺序,包括当前项目路径及类路径下的config目录和根目录。还展示了端口配置的源代码及运行结果,最后提及自定义配置文件的绑定及验证情况。

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

SpringBoot配置文件的优先级

项目结构

在这里插入图片描述

配置文件的优先级

application.properties 和 application.yml 文件按照优先级从大到小顺序排列在以下四个位置:

  1. file:./config/ (当前项目路径config目录下);
  2. file:./ (当前项目路径下);
  3. classpath:/config/ (类路径config目录下);
  4. classpath:/ (类路径config下).

在这里插入图片描述

源代码展示:

public class ConfigFileApplicationListener
		implements EnvironmentPostProcessor, SmartApplicationListener, Ordered {
// Note the order is from least to most specific (last one wins)
private static final String DEFAULT_SEARCH_LOCATIONS = "classpath:/,classpath:/config/,file:./,file:./config/";

// 省略其它代码
}

以端口配置为例

  • 在resources/config目录下配置文件设置端口为8888;
  • 在resources/目录下配置文件设置端口为8080;
  • 在类路径config目录下配置文件设置端口为6666;
  • 在类路径下配置文件设置端口为5555;

运行结果:

在这里插入图片描述

自定义配置文件的绑定

  1. CustomizedFile 类

    /**
     * 自定义配置文件, 需要配合使用后@Configuration和@PropertySource("classpath:customized-file.properties")来指定
     * @author fengxuechao
     */
    @Configuration
    @ConfigurationProperties(prefix = "customizedFile")
    @PropertySource("classpath:customized-file-${spring.profiles.active}.properties")
    public class CustomizedFile {
        private String name;
        private String author;
        private String path;
        private String description;
        // 省略 setter/getter
    }
    

    看到 ${spring.profiles.active},聪明的你一定知道这是 spring boot多环境自定义配置文件的实现方式。
    生效的配置文件是 ${spring.profiles.active} 所指定的配置文件,本文案例中生效的是 customized-file-dev.properties
    接下来继续创建配置文件验证

  2. customized-file.properties

    customizedFile.name=自定义配置文件名
    customizedFile.author=作者名
    customizedFile.path=路径地址
    customizedFile.description=看到这个就表明自定义配置文件成功了
    
  3. customized-file-dev.properties

    customizedFile.description=DEV:看到这个就表明自定义配置文件成功了
    
  4. 运行结果:

    在这里插入图片描述

    结论:只有 customized-file-dev.properties 中配置的属性生效

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值