24.6.3 Multi-profile YAML documents
你可以在单个文件中定义多个特定配置(profile-specific)的YAML文档,并通过spring.profiles
标示生效的文档,例如:
server:
address: 192.168.1.100
---
spring:
profiles: development
server:
address: 127.0.0.1
---
spring:
profiles: production
server:
address: 192.168.1.120
在以上例子中,如果development
profile被激活,server.address
属性将是127.0.0.1;如果development
和production
profiles没有启用,则该属性的值将是192.168.1.100。
在应用上下文(application context)启动时,如果没有明确指定激活的profiles,则默认的profiles将生效。所以,在下面的文档中我们为security.user.password设置了一个值,该值只在"default" profile中有效:
server:
port: 8000
---
spring:
profiles: default
security:
user:
password: weak
然而,在这个示例中,由于没有关联任何profile,密码总是会设置,并且如果有必要的话可以在其他profiles中显式重置(override):
server:
port: 8000
security:
user:
password: weak
通过!可以对spring.profiles指定的profiles进行取反(negated,跟java中的!作用一样),如:
@Profile({"!test","!wo-data-init"})
如果negated和non-negated profiles都指定一个单一文件,至少需要匹配一个non-negated profile,可能不会匹配任何negated profiles。如:
启动时指定spring.profiles.active=prod
my:
servers:
- dev.bar.com
- foo.bar.com
names: dev-bar,foo-bar
---
spring:
profiles: prod
my:
servers:
- prod.bar.com
- prod.foo.bar.com
@Component
@Profile({"!prod", "prod"})
@ConfigurationProperties(prefix="my")
public class Config {
private List<String> servers = new ArrayList<>();
private String names;
public List<String> getServers() {
return servers;
}
public String getNames() {
return names;
}
public void setNames(String names) {
this.names = names;
}
}
最后servers
为[prod.bar.com, prod.foo.bar.com]