Search code examples
springtogglz

Using togglz to implement feature flags based on environment (dev, qa, prod)


I am implementing feature flags in my spring application and I would like to use togglz. I would like the features to be based on the environment. For example a feature is being worked or tested so I could have it on in DEV and QA, but it's not ready for the public, so it's turned off in PROD.

I'm looking through the togglz doc and their activation strategies, but none of them seem to be based on the environment. Do I need to implement a custom strategy or can I use one of the existing strategies in a creative way?

If there any concise example that would be most helpful.


Solution

  • Option 1

    There is an existing activation strategy by profile provided by togglz-spring-core : SpringProfileActivationStrategy

    Option 2

    If you want to create yours, it can be achieved easily :

    @Configuration
    public class ProfileStrategy implements ActivationStrategy {
    
    
        private static final String PROFILE_PARAM = "profile";
        private final Environment environment;
    
        public ProfileStrategy(Environment environment) {
            this.environment = environment;
        }
    
        @Override
        public String getId() {
            return "profile";
        }
    
        @Override
        public String getName() {
            return "Profile strategy";
        }
    
        @Override
        public boolean isActive(FeatureState featureState, FeatureUser featureUser) {
            String profile = featureState.getParameter(PROFILE_PARAM);
            return profile != null && Arrays.asList(environment.getActiveProfiles()).contains(profile);
        }
    
        @Override
        public Parameter[] getParameters() {
            return new Parameter[] {
                ParameterBuilder.create(PROFILE_PARAM)
                    .label("Profil")
                    .description("Profile to activate feature")
                    .largeText()
            };
        }
    }