MCMXCIVR
MCMXCIVR

Reputation: 13

Spring configuration based on multiple active profiles

My app contains a split of 2 different target environments, say Linux and Windows and a split for DTAP as well. Is it possible to load different property files based on multiple active profiles?

Our current setup contains a folder structure which is processed using ant:

The goal is to have something like {OS-active}-{environment-active}-application.properties. To load the correct properties for one of the 8 active environments but to also have the base properties active based on the OS.

Is there a way to do this with Spring out-of-the-box using Spring profiles?

Upvotes: 1

Views: 2083

Answers (1)

Brother
Brother

Reputation: 2210

I would have my implementation of properties:

@Bean
@Primary
fun properties(context: AbstractApplicationContext?): PropertySourcesPlaceholderConfigurer {
    val propertySourcesPlaceholderConfigurer = PropertySourcesPlaceholderConfigurer()

    val yaml = YamlPropertiesFactoryBean()
    val os = System.getProperty("os.name").replace(" ", "")

    val resources = context?.environment?.activeProfiles
        ?.map { profile ->
            ClassPathResource("$os-$profile-application.yml")
        }?.plus(ClassPathResource("$os-base-application.yml"))
        ?.toTypedArray()?: emptyArray()

    yaml.setResources(*resources)

    propertySourcesPlaceholderConfigurer.setProperties(yaml.`object`!!)
    return propertySourcesPlaceholderConfigurer
}

For example, on MacOS you would end up with:

MacOSX-test-application.yml
MacOSX-base-application.yml

It is in Kotlin, but I think you have the idea!

Upvotes: 1

Related Questions