Assume that you have these application-{env}.yml
config profiles in resources
folder, and we are going to activate the dev
configuration.
application.yml
application-dev.yml
application-prod.yml
application-test.yml
...
There are two ways you can activate the dev
:
- modify your
application.yml
,
spring:
profiles:
active: dev
- or by command line when you want to start your application :
java -jar -Dspring.profiles.active=dev application.jar
Then, try this code in your program:
// get the active config dynamically
@Value("${spring.profiles.active}")
private String activeProfile;
public String readActiveProfilePath() {
try {
URL res = getClass().getClassLoader().getResource(String.format("application-%s.yml", activeProfile));
if (res == null) {
res = getClass().getClassLoader().getResource("application.yml");
}
File file = Paths.get(res.toURI()).toFile();
return file.getAbsolutePath();
} catch (Exception e) {
// log the error.
return "";
}
}
The output will be an absolute path of application-dev.yml