Spring Boot 读取外部配置文件 application.properties

本文介绍了Spring Boot在运行时如何读取外部的application.properties配置文件,详细阐述了Spring Boot默认加载配置文件的顺序,包括jar包内/config目录、当前目录、classpath中的config目录及classpath根目录。并提及可以通过设置'spring.config.location'来指定自定义路径的配置文件。

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

在使用Spring Boot 进行开发时, 有时候我们需要让程序在运行时读取外部的配置文件application.properties.

Spring Boot 默认加载配置文件的顺序

1. jar 包所在路径的 /config 文件夹 中的 配置文件

2. 当前文件夹下的配置文件

3. classpath 中的 config 文件夹中的配置文件

4. classpath root 中的配置文件

这是spring 读取配置文件的标准顺序。如果需要让spring 读取一个自定义路径下的配置文件,可以配置“spring.config.location”这个值。

 

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

// set spring.config.location here if we want to run the application as a jar
public static void main(String[] args) {

    new SpringApplicationBuilder(Application.class)
    .sources(Application.class)
    .properties(getProperties())
    .run(args);
}

// set spring.config.location here if we want to deploy the application as a war on tomcat
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder springApplicationBuilder) {
    return springApplicationBuilder
    .sources(Application.class)
    .properties(getProperties());
}
static Properties getProperties() {
  Properties props = new Properties();   
  props.put("spring.config.location","file:///D:/file_dir/application.properties");
return props;
}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值