来自documentation在 Spring 启动 YAML 配置上:
If a YAML document contains a
spring.profiles
key, then the profiles value (a comma-separated list of profiles) is fed into the SpringEnvironment.acceptsProfiles()
method. If any of those profiles is active, that document is included in the final merge...
因此 spring.profiles
键具有 OR 逻辑。如果将其设置为 test,dev
,则当 Spring 配置文件包含 test
或 dev 时,将应用该配置。
我想要的是AND逻辑。我有多种机器类型和区域,并且我想在机器类型和区域的特定组合上启用某些配置,例如生产,欧洲
。
是否可以根据 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。
关于java - 用于配置文件组合的 Spring boot YAML 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56441487/