Enrique Recarte
Enrique Recarte

Reputation: 33

How can I load a `application-{profile}.yml` property source without using `spring.profiles.active`?

I'm trying to integrate an existing application with Spring Boot. One of the things I'd like to do is clean up the way we load property files by having the usual Spring Boot application configuration file like this:

├── application.yaml ├── application-DEV.yaml

The thing is that I can't add the system property spring.profiles.active because I'm relying on some existing infrastructure which has a system property with the name environment instead. I'm trying an alternative solution to set the active profile by using an ApplicationContextInitializer which according to the documentation:

Typically used within web applications that require some programmatic initialization of the application context. For example, registering property sources or activating profiles against the context's environment.

This is my code which tries to add an active profile by reading the environment system property:

  @Slf4j
  public class AddEnvironmentProfileApplicationContextInitializer implements ApplicationContextInitializer {

     @Override
     public void initialize(ConfigurableApplicationContext applicationContext) {
        String environment = System.getProperty("environment");
        log.info("Adding active profile from System Property environment={}", environment);
        applicationContext.getEnvironment().addActiveProfile(environment);
     }
  }

which I'm loading with a starter dependency by defining the initializer in spring.factories with the key org.springframework.context.ApplicationContextInitializer.

If I run the application with -Denvironment=DEV, I can see that the DEV profile is added correctly, but the application-DEV.yml file is not loaded.

Am I missing something? I did inspect the source code for Spring Boot and it looks like the Property Sources are configured before running the Initializers, but then why would you define a profile with it if the right files are not loaded? Is this the desired behaviour or is it maybe a bug?

Upvotes: 3

Views: 1729

Answers (1)

Amit Phaltankar
Amit Phaltankar

Reputation: 3424

If you don't want to set a spring.profile.active as a system property you can simply do this in your default yml.

spring:
  profile:
    active: ${environment}

Upvotes: 2

Related Questions