Search code examples
javaspring-bootconfiguration-files

How to use SpringBoot PropertySource to read from an external configuration file


I've created a configuration class that will store configuration values. These configuration values should be read in from a configuration file "config.properties". Below is the config class:

@Configuration
@ComponentScan(basePackages = {"com.boot.Training.*"})
@PropertySource("file:/src/main/java/config.properties")
public class AppConfig {

    @Value("${myFirstName}")
    private static String myFirstName;

    @Value("${myLastName}")
    private static String myLastName;

    public static void showVariables() {
        System.out.println("firstName: " + myFirstName);
        System.out.println("lastName: " + myLastName);
    }

}

And below are the contents of the config.properties file:

myFirstName=John    
myLastName=Doe

Running my program should simply print the values of these variables. But instead, Eclipse tells me it cannot find the config.properties file, even though I specified that it is located in /src/main/java/config.properties .

I'm likely specifying the file location without taking something else into account. What am I missing here?


Solution

  • The location you are using (file:/src/main/java/config.properties) refers to an absolute path rather than one relative to your project home.

    A more common way to do this is to ship config.properties as part of your project in a resources directory, and refer to it via the classpath. If you move it to /src/main/resources/config.properties, you can load it this way:

    @PropertySource("classpath:config.properties")
    

    I believe in theory you could just leave it in /src/main/java and change your @PropertySource location to what I have above, but moving it to /resources is the more idiomatic way of doing this.