[英]Spring boot YAML config for combinations of profiles
從Spring啟動YAML配置的文檔 :
如果YAML文檔包含
spring.profiles
鍵,則配置文件值(以逗號分隔的配置文件列表)將輸入SpringEnvironment.acceptsProfiles()
方法。 如果其中任何一個配置文件處於活動狀態,那么該文檔將包含在最終合並中...
所以spring.profiles
鍵有OR邏輯。 如果將其設置為test,dev
,則在Spring配置文件包含test
或dev時應用配置。
我想要的是AND邏輯。 我有多種機器類型和區域,我想在機器類型和區域的特定組合上啟用一些配置,例如production,Europe
。
是否可以根據YAML文件中的配置文件組合設置配置?
我相信這更適合ApplicationListener
或EnvironmentPostProcessor
:
例如,您的AND
邏輯可能是:
@Component
public class MyListener {
@EventListener
public void handleContextStart(ApplicationPreparedEvent event) {
ConfigurableEnvironment env = event.getApplicationContext().getEnvironment();
if (env.acceptsProfiles(Profiles.of("test")) && env.acceptsProfiles(Profiles.of("test"))) {
// Do the AND configuration here.
}
}
}
或者,您可以創建自己的@ConfigurationProperties
: https : //docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties
並在@PostConstruct
方法中,在那里進行進一步的自定義:
@ConfigurationProperties("myKey")
public class MyProperties implements EnvironmentAware {
private Environment Environment;
private MachineType machineType;
private String region;
@Override
public setEnvironment(Environment environment) {
this.environment = environment;
}
enum MachineType {
MAC_OS,
WINDOWS,
LINUX
}
@PostConstruct
void init() {
if (environment.acceptProfiles(Profiles.of("dev"))) {
// Do some work setting other properties
if (machineType == MachineType.WINDOWS) {
// some other work if it's Windows
}
}
}
}
然后在整個應用程序中使用MyProperties
bean。
是的,可以根據YAML中的配置文件組合設置配置。
spring:
profiles:
active: "production,Europe"
---
spring:
profiles: production
one: prd one
two: prd two
three: prd three
---
spring:
profiles: Europe
one: EU one
four: EU four
會給你
one: EU one // <------
two: prd two
three: prd three
four: EU four
但如果你顛倒了訂單(主動:“歐洲,生產”)
你得到
one: prd one // <------
two: prd two
three: prd three
four: EU four
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.