如何获取@PropertySource()中类路径的父目录

问题描述 投票:0回答:1

我需要为我的应用程序输入一些变量,我想将该文件从资源文件夹移动到基本目录以使其更加用户友好。但是,我无法访问它,似乎是因为我无法根据需要导航到父目录。

这是我的带有变量的类

@Configuration
@ConfigurationProperties(prefix = "run")
@PropertySource("classpath:../../options.properties")
@Data
public class RunProperties {
    private String action;
    private String league;
    private Integer weeks;
    private String oldName;
    private String newName;
    private Integer numberOfPlayers;
}

打印出类路径后,我确信我处于正确的级别。我也尝试过 1 '.'而不是 2。我认为像 getParent() 方法这样的方法在这里不起作用。

如何从项目基本文件夹中的文件注入属性?

java spring-boot directory-structure properties-file
1个回答
0
投票

您可以在@PropertySource注解中使用file:前缀来代替classpath:。这允许您指定相对于项目基目录的文件路径。另外,请将 options.properties 文件保留在项目的基本目录中。

@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;
}
© www.soinside.com 2019 - 2024. All rights reserved.