25. Profiles
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 添加激活的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
运行时,proddb
和prodmq
profiles也被激活了:
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了解细节。