如何防止某些个人资料设置属性

时间:2018-06-04 06:57:51

标签: spring spring-boot

我们希望通过发送他/她希望在登录请求中拥有的角色来实现一项功能,使用户能够在系统中选择一个角色。

此功能用于测试(在客户系统中创建测试用户或将角色分配给现有的角色是“不可能的”),当然,永远不应该部署到生产环境。

如果属性feature.choose-role设置为true并且spring active profile设置为production,我希望部署我的应用程序失败。

由于我们使用的是spring config-server功能,我还希望应用程序在运行时将属性设置为true时完全停止工作。

我的第一次尝试是简单地创建此配置:

@Configuration
public class FeatureToggleGuardConfig {

    @Bean
    @RefreshScope
    @ConditionalOnProperty(value = "feature.choose-roles", havingValue = "true")
    @Profile("production")
    public Object preventDeploymentOfRoleChoosingFeatureOnProduction() {
        throw new RuntimeException("feature.choose-roles must not be true in production profile!");
    }
}

如果在部署时将属性设置为true,则此方法有效,但据我了解,如果有人实际尝试使用它,则只会尝试刷新bean - 这将永远不会发生。

另外 - 如果在使用它时只是抛出一个运行时异常,我认为它不会停止整个应用程序。

简而言之:

我想阻止我的应用程序运行(或继续运行),如果在任何时候,属性feature.choose-roles为真且活动配置文件为“生产”。

我不想改变生产代码(if(feature is enables && profile is production)等)。

1 个答案:

答案 0 :(得分:0)

Perhaps instead of having a your profile drive some sort of blocker, you can have your profile drive a config bean which says whether or not to use the feature. Then, have the nonProd config read from your property, and have the prod config always return false.

Something like:

public interface ChooseRolesConfig {

    boolean allowChoosingRoles();
}

@Profile("!production")
public class NonProdChooseRolesConfig implements ChooseRolesConfig {

    @Value("${feature.choose-roles}")
    boolean chooseRoles;

    @Override
    public boolean allowChoosingRoles() {
        return chooseRoles;
    }
}

@Profile("production")
public class ProdChooseRolesConfig implements ChooseRolesConfig {

    @Override
    public boolean allowChoosingRoles() {
        return false;
    }
}

and then just autowire a ChooseRolesConfig object, and call the method, and regardless of what you change feature.choose-roles to using cloud config, it should always be false for prod.

Disclaimer: I blindly wrote this so it might be missing some annotations or something but hopefully you get the idea

相关问题