Spring Boot - Change Application Properties File Name & Directory

This tutorial shows you how to set a custom name for the application properties file in Spring Boot.

Spring allows you to store configuration on an application.properties or application.yml file. That allows you to run the application using different configurations based on the environment. Normally, the file name should be application with .properties or .yml/.yaml extension since Spring will look for a file with the matching name and extension in the src/main/resources directory. However, if you really need to use a different file name or directory for any reason, it's possible to use a custom one.

Set Custom Application Properties File Name

To use a custom properties file name, set the value of spring.config.name property. You can do it by calling Java's System.setProperty method before starting the Spring application.

  public static String setProperty(String key, String value)

The value of the property is the file name without the extension. For example, if the file name is env.properties or env.yml, set the value to env.

  @SpringBootApplication
  public class MyApplication {
  
    public static void main(String[] args) {
      System.setProperty("spring.config.name", "env");
      new SpringApplicationBuilder(MyApplication.class).run(args);
    }
  }

You may already know that Spring allows profile-specific properties files. By setting the value of spring.config.name property, it also affects the profile-specific properties files. For example, using the example above, the file name for staging profile will be env-staging.

Set Custom Application Properties File Directory

The directory of the properties file can be customized as well. By default, Spring will use src/main/resources as the directory. To change it, you can set the spring.config.additional-location property. The passed value can be a relative or absolute path to the directory. If you use a relative path, it must be relative to the project's root directory. In addition, to represent a directory, the value must end with /.

  @SpringBootApplication
  public class MyApplication {
  
    public static void main(String[] args) {
      System.setProperty("spring.config.additional-location", "woolha-demo-application-properties/src/main/resources/myconfig/");
      new SpringApplicationBuilder(MyApplication.class).run(args);
    }
  }

Summary

The file name and the directory of the application properties file can be changed by setting property values which can be done programmatically before running the Spring application. You have to set the spring.config.name property to change the file name and spring.config.additional-location to change the directory.