javaspring-bootdirectory-structureproperties-file

How to get parent directory of classpath inside @PropertySource()


I have some variables that need to be inputted for my app and I wanted to move that file from the resources folder to the base directory to make it more user friendly. However, I am having trouble accessing it, seemingly because I am unable to navigate to the parent directory as I need to.

Here is my class with the variables

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

I am sure that I am at the right level after printing out the classpath. I have also tried with 1 '.' instead of 2. I assume that something like the getParent() method won't work here.

How do I inject properties from a file in the base folder of my project?


Solution

  • You can use the file: prefix in the @PropertySource annotation instead of classpath:. This allows you to specify the path to the file relative to the base directory of your project. Also, keep the options.properties file in the base directory of your project.

    @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;
    }