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

如何通过@PropertySource读取项目根目录下的properties配置文件?

解决Spring Boot加载项目根目录配置文件的问题

核心原因

classpath:前缀指向的是编译后的类路径目录(比如Maven项目的target/classes),项目根目录不在类路径范围内,所以用../../这种相对路径根本没法跳出类路径访问外部文件。

可行解决方案

1. 用文件系统路径直接加载

修改@PropertySource的路径,改用file:前缀指向项目根目录的配置文件:

@Configuration
@ConfigurationProperties(prefix = "run")
@PropertySource("file:./options.properties")
@Data
public class RunProperties {
    private String action;
    private String league;
    private Integer weeks;
    private String oldName;
    private String newName;
    private Integer numberOfPlayers;
}
  • ./代表当前工作目录,开发阶段就是你的项目根目录;如果打包成Jar运行,要保证Jar文件和options.properties在同一目录下,或者换成绝对路径(比如file:/opt/app/options.properties)。

2. 通过启动参数指定配置文件

不需要修改代码,启动项目时添加spring.config.location参数,让Spring Boot自动加载根目录的配置文件:

# Maven开发环境启动
mvn spring-boot:run --spring.config.location=file:./options.properties

# Jar包启动
java -jar your-app.jar --spring.config.location=file:./options.properties

这种方式更灵活,不用硬编码路径,还能同时加载多个配置文件。

3. 自定义配置加载逻辑(进阶)

如果需要更复杂的加载规则(比如根据环境自动匹配路径),可以实现PropertySourceLocator接口:

@Component
public class CustomPropertySourceLocator implements PropertySourceLocator {
    @Override
    public PropertySource<?> locate(Environment environment) {
        File configFile = new File("./options.properties");
        if (configFile.exists()) {
            try {
                Properties properties = new Properties();
                properties.load(new FileInputStream(configFile));
                return new PropertiesPropertySource("custom-options", properties);
            } catch (IOException e) {
                throw new RuntimeException("加载根目录配置文件失败", e);
            }
        }
        return null;
    }
}

配置好后,Spring Boot启动时会自动调用这个类加载配置文件,RunProperties上的@PropertySource可以直接去掉。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 02:47:19