This tutorial will show how to load multiple configuration files from different directories with Spring Boot.
By default, Spring Boot look for your externalized configuration file ( application.proroperties ) in four predetermined locations :
- in classpath root,
- in the package /config in classpath,
- in the current directory
- in /config subdirectory of the current directory.
You may want to load multiple externalized configuration files located in different directories. This tutorial will show how to do it.
Example
Consider the following project structure :
application.properties and conf.properties are two configuration files we want to load in our Spring Boot application.
Command line arguments
The first way to tell Spring Boot to load our configuration files is by using command arguments. Spring Boot provides the argument spring.config.name to set configuration files names seperated with a comma. The second command line argument is spring.config.location in which you must set the locations where Spring Boot will find your externalized configuration files.
Below the usage in our situation :
1 2 |
java -jar myproject.jar --spring.config.name=application,conf --spring.config.location=classpath:/external/properties/,classpath:/com/roufid/tutorial/configuration/ |
Spring Boot will now pick up application.properties from /com/roufid/tutorial/configuration/ and conf.properties from /external/properties/.
Environment variables
You can use environment variables to tell Spring Boot to pick up what you want where you want. set the name of your externalized configuration files in the SPRING_CONFIG_NAME environment variable seperated with a comma and the locations in SPRING_CONFIG_LOCATION.
Below an example :
1 2 3 |
set SPRING_CONFIG_NAME=conf set SPRING_CONFIG_LOCATION=classpath:/external/properties/,classpath:/com/roufid/tutorial/configuration/ java -jar myproject.jar |
Programmatically
You can programmatically tell Spring Boot to load your configuration files from custom location as below :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.roufid.tutorial; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.env.ConfigurableEnvironment; @SpringBootApplication public class Application { public static void main(String[] args) { ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(Application.class) .properties("spring.config.name:application,conf", "spring.config.location:classpath:/external/properties/,classpath:/com/roufid/tutorial/configuration/") .build().run(args); ConfigurableEnvironment environment = applicationContext.getEnvironment(); System.out.println(environment.getProperty("app.firstname")); System.out.println(environment.getProperty("conf.lastname")); } } |