弹簧配置文件:拒绝用户tu运行来自同一“组”的许多配置文件

时间:2019-07-10 18:20:30

标签: spring

我想整理护发素。 例如,我有两组配置文件: a)开发,生产,测试 b)ProfileDB1,ProfileDB2,ProfileDB3

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

2 个答案:

答案 0 :(得分:1)

您可以编写某种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");
        }
    }
}

答案 1 :(得分:1)

您可以添加一个ApplicationListener,以检查何时准备应用程序,以确保在其余应用程序加载之前配置文件符合预期。

public class ProfileValidator implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    private static final Logger LOG = LoggerFactory.getLogger(ProfileValidator.class);

    private static final Set<String> DB_PROFILES = new HashSet<>(Arrays.asList("DB1", "DB2", "DB3"));

    private static final Set<String> ENVIRONMENT_PROFILES = new HashSet<>(Arrays.asList("dev", "test"));


    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent applicationEnvironmentPreparedEvent) {
        List<String> activeProfiles = Arrays.asList(applicationEnvironmentPreparedEvent.getEnvironment().getActiveProfiles());

        LOG.info("Validating Allowed Profiles - {}", activeProfiles);

        if (activeProfiles.size() > 1) {
            long count = activeProfiles.stream().filter(profile -> DB_PROFILES.contains(profile) || ENVIRONMENT_PROFILES.contains(profile)).count();

            LOG.debug("Counted {} profiles", count);

            if (count != 0 && activeProfiles.size() - 2 != (activeProfiles.size() - count)) {
                throw new IllegalArgumentException(String.format("Invalid Profiles detected for %s", activeProfiles.toString()));
            }
        }
    }
}

这是一个可行的示例,

https://github.com/DarrenForsythe/spring-profile-validator

注意spring.factories以注册ApplicationListener。还有一个测试类可以验证功能,可以通过无效的组合启动它。