首页 > 解决方案 > Spring 配置文件:拒绝用户运行来自同一“组”的许多配置文件

问题描述

我想调节配置文件。例如,我有两组配置文件:a)DEV、PROD、TEST b)ProfileDB1、ProfileDB2、ProfileDB3

我想强制该应用程序将使用第一组的一个配置文件和第二组的一个配置文件运行。但没有了。可能吗 ?

标签: spring

解决方案


您可以编写某种 ActiveProfilesVerifier 组件,在其中Environment注入并验证活动配置文件:

@Component
public class ActiveProfilesVerifier {

    private static final List<String> ENV_PROFILES = Arrays.asList("DEV", "PROD", "TEST");
    private static final List<String> DBASE_PROFILES = Arrays.asList("ProfileDB1", "ProfileDB2", "ProfileDB3");

    private final Environment environment;

    public ActiveProfilesVerifier(Environment environment) {
        this.environment = environment;
    }

    @PostConstruct
    public void verifyProfiles() {
        String[] activeProfiles = environment.getActiveProfiles();

        boolean hasSingleEnvProfile = Arrays.stream(activeProfiles).filter(ENV_PROFILES::contains).count() == 1;
        if (!hasSingleEnvProfile) {
            throw new IllegalArgumentException("Select exactly one environment profile");
        }

        boolean hasSingleDbaseProfile = Arrays.stream(activeProfiles).filter(DBASE_PROFILES::contains).count() == 1;
        if (!hasSingleDbaseProfile) {
            throw new IllegalArgumentException("Select exactly one database profile");
        }
    }
}

推荐阅读