Warm tip: This article is reproduced from serverfault.com, please click

Is it possible to have application.properties depend on multiple profiles?

发布于 2019-12-16 11:56:36

Is it possible to have a Spring Boot properties file depend on two or more profiles? Something like application-profile1-profile2.properties?

Questioner
EnlightMe
Viewed
0
kyakya 2020-12-23 22:08:02

There are 4 ways I know.

  1. insert .yaml or .properties programmatically like Asi Bross Said. Use ResourceLoader or YamlPropertySourceLoader to insert.

  2. Use .yaml. but it will be replace when you have a another spring project to dependent it.

  3. Use properties instead of profiles. (For api project)

    1. Use one @PropertySource to define properties file A.
    2. Get the variables from properties file A and assign them to the parameters in another @PropertySource file path expression.

    For example:

    resources
    /-application.properties  <-- remove or empty,because it will be override by application project
    /-moduleA
         /-application.properties               <-- Intellij can identify properties files started with application-
         /-application-mysql-dev.properties
         /-application-psql-dev.properties
         /-application-psql-prod.properties
    

    The content of resources/moduleA/application.properties :

    moduleA.custom.profile1=mysql
    moduleA.custom.profile2=dev
    

    Content of Java Config file:

    @SpringBootApplication
    @PropertySources({
            @PropertySource("/moduleA/application.properties"),
            @PropertySource("/moduleA/application-${moduleA.custom.profile1}-${moduleA.custom.profile2}.properties"),
    })
    public class ModuleConfig {}
    
  4. Use properties instead of profiles. (For application project)

    resources
    /-application.properties
    /-application-mysql-dev.properties
    /-application-psql-dev.properties
    /-application-psql-prod.properties
    

    The content of resources/application.properties :

    moduleA.custom.profile1=mysql
    moduleA.custom.profile2=dev
    

    The content of SpringMvcApplication.java:

    @SpringBootApplication
    @PropertySource("/application-${moduleA.custom.profile1}-${moduleA.custom.profile2}.properties")
    public class SpringMvcApplication {...}