How to load external property files into Spring Boot application?
It is a standard practice that during our production deployments, our application loads property files
from external locations. This helps us to change our configurations without changing our code. In this page, we will come to
know how to load external property files into Spring Boot application.
By default, Spring Boot look for externalized default property file application.properties into given below
predetermined locations:
-- In the classpath root.
-- In the package "/config" in classpath.
-- In the current directory.
-- In the "/config" directory of current folder.
Now lets say, your application requires externalized properties like application.properties and another property
file myapp.properties. The both properties can be in the same folder or they can be in different folder. There are 3 ways of doing it.
Command line arguments
In the first approach, all you need to do is pass folder names and property names as part of command line arguments
as shown below:
Terminal |
java -jar myapp.jar --spring.config.name=application,myapp
--spring.config.location=classpath:/data/myapp/config,classpath:/data/myapp/external/config
|
In the above command, we are passing property file name as part of "--spring.config.name" variable
and folder location as part of "--spring.config.location" variable.
Environment variables
In the second approach, you can configure your externalized configuration details into environment variables
and your Spring Boot application will read it from your environment as shown below:
Terminal |
set SPRING_CONFIG_NAME=application,myapp
set SPRING_CONFIG_LOCATION=classpath:/data/myapp/config,classpath:/data/myapp/external/config
java -jar myapp.jar
|
Programatically loding configurations
SpringBootWebApplication |
package com.java2novice.springboot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 SpringBootWebApplication {
private static Logger logger = LoggerFactory.getLogger(SpringBootWebApplication.class);
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext applicationContext = new SpringApplicationBuilder(SpringBootWebApplication.class)
.properties("spring.config.name:application,myapp",
"spring.config.location:classpath:/data/myapp/config,classpath:/data/myapp/external/config")
.build().run(args);
ConfigurableEnvironment environment = applicationContext.getEnvironment();
logger.info(environment.getProperty("cmdb.resource-url"));
}
}
|
Output |
2017-11-22 22:44:24.775 INFO 29696 --- [ main] c.j.springboot.SpringBootWebApplication : http://java2novice.com
|
|