Profiles
Spring Profiles提供了一种隔离应用程序配置的一部分,并使其中只在某些环节中可用的方案.任何@Component或@Configuration可以用@Profile标记已限制加载时机:
@Configuration
@Profile("production")
public class ProductionConfiguration {
// ...
}
在正常的Spring方法中,可用使用spring.profiles.active Environment属性指定哪些配置文件是激活的.你可以以任何常规方式指定属性.例如,你可以将其包含在application.properties中:
spring.profiles.active=dev,hsqldb
或在命令行使用开关--spring.profiles.active = dev,hsqldb指定。
25.1 添加激活的profiles
spring.profiles.active属性遵循其他属性相同的排序规则,最高级别的PropertySource值会覆盖其他的值.这意味着你可以在application.properties文件中指定激活的配置文件,然后使用命令行开关替换他们
有的时候只是希望将 profile-specific配置文件的属性添加到激活的配置文件中而不是替换它们.spring.profile.include属性可以用于无条件添加激活的配置文件.SpringApplication入口点还有一个java api用于设置其他配置(即在由spring.profiles.active属性激活的配置文件之上):参考setAdditionalProfiles()方法。
例如,当使用switch --spring.profiles.active = prod运行具有以下属性的应用程序时,proddb和prodmq配置文件也将被激活:
---
my.property: fromyamlfile
---
spring.profiles: prod
spring.profiles.include:
- proddb
- prodmq
请记住,可以在YAML文档中定义spring.profiles属性,以确定此特定文档何时包含在配置中。 有关更多详细信息,请参见第70.7节“根据环境更改配置”。
25.2 以编程方式设置配置文件
您可以通过在应用程序运行之前调用SpringApplication.setAdditionalProfiles(...)以编程方式设置活动配置文件。 也可以使用Spring的ConfigurableEnvironment接口激活概要文件。
25.3 Profile-specific配置文件
通过@ConfigurationProperties引用的application.properties(或application.yml)和文件的概要文件特定变体被视为加载文件。 有关详细信息,请参见第24.4节“Profile-specific属性”。