Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Profiles application properties order

We have many environments that have multiple active Spring profiles, but what is the precedence of the application-{profile}.yml files?

If I have spring.profiles.active=test-us-west-2-p1, test-us-west-2, test

In what order do the files application-test.yml, application-test-us-west-2.yml, application-test-us-west-2-p1.yml get loaded? If I have the same property in each file, which "wins"?

Also, has this changed from Spring-Boot 1.5.x to 2.x? It seems like it may have.

like image 400
Gandalf Avatar asked Jul 27 '18 20:07

Gandalf


2 Answers

The profile's properties are loaded in the same order as you specify them, and if the same property is defined in different profiles the last one wins.

This behavior applies to both Spring Boot versions 1.5.x and 2.x, and if I recall correctly, it applies to all versions of Spring.

Spring always loads appication.yml. And afterwards, if some profile is specified, it will load that profile's property file. And if after that profile another profile is specified, it will load that profile's propperty file. Always overriding current properties's value with the new one.

So, let's say you have profile1 and profile2. And you have these property files:

application.yml:

property1: bob
property2: alice
property3: eve

application-profile1.yml:

property2: alice1
property3: eve1

application-profile2.yml:

property3: eve2

And you start your application with: spring.profiles.active=profile1, profile2

Your will get:

property1: bob
property2: alice1
property3: eve2
like image 170
f-CJ Avatar answered Oct 18 '22 07:10

f-CJ


First of all, we need to find out the final set of all active profiles. There are ways of setting/replacing active profiles and adding active profiles on top of existing active ones. For instance, active profiles set with the spring.profiles.active property are replaced with the -Dspring.profiles.active command line option. (And this can get really complex.)

On the other hand, the SpringApplicationBuilder's profiles method adds to the existing active profiles. We can use the following code to figure out the final set of active profiles:

@Autowired
private Environment environment;

...

System.out.println("Active profiles: " +
        Arrays.toString(environment.getActiveProfiles()));

Now we have to consider what Spring documentation calls last-wins strategy.

If several profiles are specified, a last-wins strategy applies.

So, if we have the following code and all other options excluded:

new SpringApplicationBuilder(Application.class)
        .profiles("dev", "prod")
        .run(args);

both application-dev.properties and application-prod.properties files are loaded and the keys with the same name in the latter one (the production) override the former one.

like image 33
Jan Bodnar Avatar answered Oct 18 '22 08:10

Jan Bodnar