You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring指定Properties文件位置问题:无法加载application-local.properties

解决Spring Boot本地开发无法加载application-local.properties的问题

核心原因

你当前用@PropertySource加载application-local.properties,但Spring Boot默认的application.properties加载优先级高于手动添加的@PropertySource,导致local配置被覆盖。另外,Spring Boot原生的Profile环境配置机制是更规范的解决方案,无需手动指定配置文件。


解决方案

1. 激活Local Profile(推荐)

Spring Boot会自动识别application-{profile}.properties格式的配置文件,只要激活对应profile,就会自动加载并覆盖默认配置的同名属性。修改启动代码,直接指定激活local profile:

public class LocalDevApplication {
  public static void main(String[] args) {
    SpringApplication.from(App::main)
        .with(LocalTestConfig.class)
        .run("--spring.profiles.active=local");
  }

  @TestConfiguration(proxyBeanMethods = false)
  static class LocalTestConfig {
    @Value("${my.property}")
    private String myProperty;
  }
}

这样Spring Boot会先加载application.properties,再加载application-local.properties,local配置中的属性会覆盖默认配置。

2. 调整@PropertySource优先级(不推荐)

如果必须手动指定配置文件,需要让application-local.properties的加载顺序在application.properties之后,确保覆盖生效:

public class LocalDevApplication {
  public static void main(String[] args) {
    SpringApplication.from(App::main)
        .with(LocalTestConfig.class)
        .run(args);
  }

  @TestConfiguration(proxyBeanMethods = false)
  @PropertySources({
      @PropertySource("classpath:application.properties"),
      @PropertySource("classpath:application-local.properties")
  })
  static class LocalTestConfig {
    @Value("${my.property}")
    private String myProperty;
  }
}

注意:这种方式会替代Spring Boot的自动配置加载逻辑,灵活性较差,不建议使用。

3. 检查配置文件位置

确保application-local.properties放在src/main/resources目录下(本地开发启动时,Spring Boot会扫描该目录)。如果放在src/test/resources,只有运行测试用例时才会被加载。


内容的提问来源于stack exchange,提问作者user1555190

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 18:52:36