25. Profiles

Spring Profiles提供了一种隔离你的应用的部分配置的途径,使它只在某一环境中有效。任何@Component或者@Configuration可以被标记为@Profile来限制,当它被加载时。如下:

  1. @Configuration
  2. @Profile("production")
  3. public class ProductionConfiguration {
  4.  
  5. // ...
  6.  
  7. }

你可以使用spring.profiles.activeEnvironment属性来指定哪个profiles是激活的。你可以指定该属性以本章前面任何描述过的方式。举个例子,你可以把它包括进你的application.properties,如下:

  1. spring.profiles.active=dev,hsqldb

你可以在命令行指定,通过使用下面的开关:

  1. --spring.profiles.active=dev,hsqldb

25.1 添加激活的Profiles

spring.profiles.active属性遵循和其他属性一样的顺序规则。最高的PropertySource胜出。这意味着你你可以指定激活的profiles在application.properties里,之后使用命令行开关替换它们。

有时,将指定的profile属性添加到激活的profiles而不是取代它们很有用。spring.profiles.include属性可以被用来无条件的添加激活的profiles。SpringApplication入口点也有一个Java API来设置额外的profiles(that is, on top of those activated by the spring.profiles.active property)。查阅SpringApplicationsetAdditionalProfiles()方法。

举个例子,当一个应用使用下面的属性通过使用开关—spring.profiles.active=prod运行时,proddbprodmqprofiles也被激活了:

  1.  

my.property: fromyamlfile

spring.profiles: prod spring.profiles.include:

  • proddb
  • prodmq

记住spring.profiles属性可以被定义在一个YAML文档中,来决定什么时候这份特殊文档被加到配置里。查阅74.7 “Change Configuration Depending on the Environment”了解更多。

25.2 编程式的设置Profils

你可以编程式的激活的peofiles,在你的应用运行前通过调用SpringApplication.setAdditionalProfiles(…​)。使用Spring的ConfigurableEnvironment接口来激活profiles也是可以的。

25.3 指定的Profile(Profile-specific) 配置文件

application.properties(或者application.yml)和文件的Profile-specific变体通过@ConfigurationProperties引用,它们被认为是文件并加载。查阅24.4节, “Profile-specific Properties了解细节。