Springboot - 每个配置文件可以有多个配置文件的配置文件

11

在SpringBoot应用程序中配置多个特定于配置文件的属性文件的最佳方法。以下是一个示例:

-资源
  -- application.properties
      -- dev
            -- application-dev.properties
            -- ldap-dev.properties
            -- quartz-dev.properties
            -- etc-dev.properties
    -- 测试
            -- application-test.properties
            -- ldap-test.properties
            -- quartz-test.properties
            -- etc-test.properties
    -- 生产
            -- application-prod.properties
            -- ldap-prod.properties
            -- quartz-prod.properties
            -- etc-prod.properties

application.properties 和 application-profile.properties 文件加载正常。我正在寻找一种推荐的方法来加载其他与配置文件相关的属性文件。但我不确定是否有一种基于 profile 的方式从文件夹中加载所有属性文件?

4个回答

6

内置的配置监听器非常灵活。例如,您可以设置spring.config.name=application,ldap,quartz,etcspring.config.location=classpath:/,classpath:/dev,classpath:/prod,classpath:/test,或者等效的环境变量。Selim的答案中的链接记录了基本行为和配置选项。


4
自 Spring Boot 2.0.4 版本开始,只需将您的配置文件指定到 spring.config.name 环境变量中即可使用此功能。例如:spring.config.name=application,ldap,quartz

3

我不确定是否有更好的方法,或者我的建议是否真的有效,但你可以尝试这个:

在你的配置类之前添加@PropertySource注解。

@PropertySource("classpath:ldap-${spring.profiles.active}.properties", "classpath:quartz-${spring.profiles.active}.properties", "classpath:etc-${spring.profiles.active}.properties")

为了更好地理解Spring如何从不同的来源和配置文件中加载配置,请参考这个这个链接。
希望能对您有所帮助。

0

@PropertySources 可以用于加载多个带有配置文件的配置文件,其中包括配置文件的配置文件 ldap-${spring.profiles.active}.properties

但如果您使用的是 YAML,则 @PropertySource 将无法工作。您必须使用 @ConfigurationProperty 来加载除 application.yml 之外的 YML 文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接