【问题标题】:Spring boot profiles with external properties具有外部属性的 Spring Boot 配置文件
【发布时间】:2015-09-12 10:52:33
【问题描述】:

我想在 Spring Boot 中设置 3 个配置文件:生产、开发、使用外部配置文件进行测试。

应用类:

@SpringBootApplication
public class Application {

    public static void main(String[] args){
        SpringApplication.run( Application.class, args );
    }
}

AppConfig 类:

@Configuration
@PropertySources({
        @PropertySource("config/application.yml"),
        @PropertySource(value = "file:${external.config}")
})

@ConfigurationProperties
public class AppConfig {

}

config/application.yml:

---
spring.profiles: production
endpoints.enabled: false
---
spring.profiles: development,test
endpoints.enabled: true
info.version: @project.version@
info.test: Test dev or test
info.profile: ${spring.profiles.active}
---

external.config: ${user.home}/.myapp/application.properties

.myapp/application.properties:

spring.profiles.active=production
info.version=5

spring-boot-actuator /info的输出

{
  version: "5",
  test: "Test dev or test",
  profile: "production"
}

预期输出:

404 because of the endpoints.enabled: false

spring-boot-actuator /env

spring.profiles.active: "production"

【问题讨论】:

    标签: java spring spring-boot spring-profiles spring-boot-actuator


    【解决方案1】:

    您可能应该在 application.yml 文件前加上 classpath:

    无论如何,为什么不在java配置中直接使用spring profile来驱动配置呢? IMO,这会更干净,并使您的属性更加类型安全和重构友好,并且不容易出现拼写错误。

    更新:

    根据文档,您无法使用 @PropertySource 注释加载 yml 文件:

    http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-yaml-shortcomings

    因此,如果您需要使用文件,则需要使用纯属性文件。您可以使用here 显示的特定于属性的应用程序属性文件。

    除了 application.properties 文件,配置文件特定 也可以使用命名约定来定义属性 应用程序-{profile}.properties。

    【讨论】:

    • 嗨,我也尝试过使用类路径,没有它也可以工作。 ${external.config} 有效,顺便说一下版本:“5”值来自外部配置。我在外部配置中还有更多属性,例如:它正在工作的数据库属性。
    • 啊,你是对的。道歉。我看到您可以评估已针对 env 注册的任何配置。我会更新我的答案。
    • 我认为使用 classpath: 在不同环境中可能更安全/更可预测
    • 谢谢,第一次我以为会很容易。 :( 但是生产配置文件设置为什么没有被激活?
    • 好的,根据文档,你不能用@PropertySource docs.spring.io/spring-boot/docs/current/reference/html/…加载yml文件
    猜你喜欢
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 2017-10-26
    • 2018-02-21
    • 2015-06-26
    • 2017-06-21
    • 2015-05-14
    相关资源
    最近更新 更多