How to add multiple application.properties files in spring-boot?

前端 未结 4 1285
难免孤独
难免孤独 2020-12-05 02:21

I have a Spring boot application that is divided in several modules. The main module runs the application and has an application.properties file in the resource

4条回答
  •  情话喂你
    2020-12-05 02:47

    The problem is exactly what @geoand describes. Spring boot loads top level application.properties and ignores any properties file with the exact name located in other jars.

    But I didn't find any concrete implementation on how to fix this problem, so here it is for those who wants to know the implementation.

    Consider this project configuration:

    +main_module
      +src
        +main
          +java
            +my/package/Application.java
          +resources/application.properties
    +module_aa
      +src
        +main
          +java
            +my/package/config/ModuleAAConfig.java
          +resources/module_aa.properties
    +module_bb
      +src
        +main
          +java
            +my/package/config/ModuleBBConfig.java
          +resources/module_bb.properties
    

    Now to load properties for each sub modules correctly we need to add @PropertySource annotation on the configs of each module i.e ModuleAAConfig.java, ModuleBBConfig.java.

    Example:

    ModuleAAConfig.java

    package my.package.config;
    
    @Configuration
    @PropertySource(
        ignoreResourceNotFound = false,
        value = "classpath:module_aa.properties")
    public class ModuleAAConfig {}
    

    ModuleBBConfig.java

    package my.package.config;
    
    @Configuration
    @PropertySource(
        ignoreResourceNotFound = false,
        value = "classpath:module_bb.properties")
    public class ModuleBBConfig {}
    

    Bonus:

    If you want to load profile specific property, you can do so by utilizing spring variables e.g.

    @PropertySource("classpath:module_aa-${spring.profiles.active}.properties")
    

提交回复
热议问题