首页 > 科技 > SpringBoot中文参考指南(2.1.6)25、配置文件

SpringBoot中文参考指南(2.1.6)25、配置文件

上一篇[@ConfigurationProperties 验证]

下一篇[未完待续]

25、配置文件

Spring Profiles 提供了一种方法来隔离应用程序配置的各个部分,并使其仅在某些环境中可用。任何 @Component 或 @Configuration 都可以用 @Profile 标记,以便限制加载时间,如下面的示例所示:

@Configuration@Profile("production")public class ProductionConfiguration {    // ...}

你可以使用 spring.profiles.active Environment 属性来指定激活哪个 profiles。你可以用前面章节描述的任何方式指定属性。例如,你可以在 application.properties 中包括它,如下面示例所示:

spring.profiles.active=dev,hsqldb

通过使用 --spring.profiles.active=dev,hsqldb,你还可以在命令行上指定它。

25.1、添加活动配置文件

spring.profiles.active 属性遵循与其他属性相同的排序规则:最高的 PropertySource 获胜。这意味着你可以在 application.properties 中指定活动的 profiles,然后通过使用命令行开关替换它们。

有时,将特定 profile 的属性添加到活动的 profiles 而不是替换它们是很有用的。spring.profiles.include 属性可用于无条件添加活动的 profiles。SpringApplication 入口点还有一个用于设置其他 profiles 的 Java API(也就是说,在 spring.profiles.active 属性激活的对象之上)。请查看 SpringApplication 中的 setAdditionalProfiles() 方法。

例如,当带以下属性的应用程序通过使用开关:--spring.profiles.active=prod 运行时,proddb 和 prodmq profiles 也被激活:

---my.property: fromyamlfile---spring.profiles: prodspring.profiles.include:  - proddb  - prodmq

注释:请记住,可以在 YAML 文档中定义 spring.profiles 属性,以确定配置中何时包含此特定文档。详见第 77.7 节:根据环境更改配置。(https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/howto-properties-and-configuration.html#howto-change-configuration-depending-on-the-environment )

25.2、以编程方式设置配置文件

在运行应用程序之前,可以通过调用 SpringApplication.setAdditionalProfiles(…​)以编程方式设置活动的 profiles。也可以使用 Spring 的 ConfigurableEnvironment 接口激活 profiles。

25.3、特定 profile 的配置文件

application.properties(或 application.yml)和通过 @ConfigurationProperties 引用的文件,这两者的特定 profile 变体都被视为文件并被加载。详见第 24.4 节:特定 profile 的属性。(https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/boot-features-external-config.html#boot-features-external-config-profile-specific-properties )

上一篇[@ConfigurationProperties 验证]

下一篇[未完待续]

本文来自投稿,不代表本人立场,如若转载,请注明出处:http://www.souzhinan.com/kj/299267.html