DEV Community

Cover image for Feature Flags in Spring Boot using Aspect-Oriented Programming
Saarthak Gupta
Saarthak Gupta

Posted on

Feature Flags in Spring Boot using Aspect-Oriented Programming

In modern software development, feature flags play a crucial role in managing feature releases. By using feature flags (also known as feature toggles), developers can enable or disable features dynamically without redeploying the application. This approach enables incremental releases, controlled experimentation, and smoother deployments, especially in complex and large-scale systems.

In this blog, we'll explore how to implement feature flags in a Spring Boot application using Aspect-Oriented Programming (AOP). AOP allows us to modularize cross-cutting concerns like logging, security, and feature toggling, separating them from the core business logic. Leveraging AOP, we can design a flexible and reusable feature flag implementation that can adapt to various requirements.

We’ll demonstrate how AOP can intercept method calls, check feature flags, and conditionally execute functionality based on the flag's status. This makes the implementation cleaner, more maintainable, and easier to modify. A basic understanding of AOP, Spring Boot, and feature flags is recommended to follow along.

You can find the code referenced in this article here: Feature Flags with Spring Boot.

Setting up Feature Flags base classes

  • Assuming you already have a Spring Boot project set up, the first step is to define a FeatureFlagValidator interface. This interface will be responsible for encapsulating the logic that validates whether a feature should be enabled or disabled based on custom conditions.
public interface FeatureFlagValidator {
  boolean validate(Object... args);
}
Enter fullscreen mode Exit fullscreen mode

The validate method takes in a variable number of arguments (Object... args), which gives flexibility to pass any necessary parameters for the validation logic. The method will return true if the feature should be enabled, or false if it should remain disabled. This design allows for reusable and easily configurable feature flag validation logic.

  • Now, once we have our validator interface ready, the next step will be creating a custom FeatureFlag annotation. This annotation will be applied to methods that need to be toggled on or off based on specific conditions.
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FeatureFlag {
  Class<? extends FeatureFlagValidator>[] validators();
}
Enter fullscreen mode Exit fullscreen mode

This annotation accepts an array of FeatureFlagValidator classes, allowing for configurable logic to determine whether a feature should be enabled or disabled.

  • After this, we will finally create our aspect. This aspect class will manage feature flag validation based on the FeatureFlag annotation.
@Aspect
@Component
public class FeatureFlagAspect {
  @Autowired private ApplicationContext applicationContext;

  @Around(value = "@annotation(featureFlag)", argNames = "featureFlag")
  public Object checkFeatureFlag(ProceedingJoinPoint joinPoint, FeatureFlag featureFlag)
      throws Throwable {
    Object[] args = joinPoint.getArgs();
    for (Class<? extends FeatureFlagValidator> validatorClass : featureFlag.validators()) {
      FeatureFlagValidator validator = applicationContext.getBean(validatorClass);
      if (!validator.validate(args)) {
        throw new RuntimeException(ErrorConstants.FEATURE_NOT_ENABLED.getMessage());
      }
    }
    return joinPoint.proceed();
  }
}
Enter fullscreen mode Exit fullscreen mode

This class includes a method that

  • intercepts calls to methods annotated with @FeatureFlag, validates the feature flag using the
  • provided validators, and throws a GenericException if the validation doesn't pass.

Creating and configuring the Feature Flags classes

  • Let’s say we want to manage a Feature A using a feature flag. To do this, we need to implement the FeatureFlagValidator interface and apply it using the FeatureFlag annotation around the relevant methods.
@Component
@RequiredArgsConstructor
public class FeatureAFeatureFlag implements FeatureFlagValidator {
  private final FeatureFlagConfigs featureFlagConfigs;
  private final Logger logger = LoggerFactory.getLogger(FeatureAFeatureFlag.class);

  @Override
  public boolean validate(Object... args) {
    boolean result = featureFlagConfigs.getFeatureAEnabled();
    if (!result) {
      logger.error("Feature A is not enabled!");
    }
    return result;
  }
}
Enter fullscreen mode Exit fullscreen mode
  • FeatureAFeatureFlag: This class implements the FeatureFlagValidator interface. It contains logic that checks whether Feature A is enabled or disabled by referencing a configuration class (FeatureFlagConfigs). If the feature is disabled, a warning message is logged, which helps in monitoring and debugging.
  • Now, you must be wondering what is this FeatureFlagConfigs class in the above code. The FeatureFlagConfigs class is responsible for managing feature flags through the configuration file (such as application.properties). This class binds feature flag values from the configuration, allowing you to control which features are enabled or disabled at runtime.
@RequiredArgsConstructor
@ConfigurationProperties(prefix = "feature-flags")
@Getter
public class FeatureFlagConfigs {
  final Boolean featureAEnabled;
}
Enter fullscreen mode Exit fullscreen mode
  • Example Configuration (application.properties): You can control the state of Feature A by adding a property in your configuration file. For example, setting feature-flags.feature-a-enabled=true will enable the feature. This makes it simple to toggle features without redeploying or modifying the codebase.
feature-flags.feature-a-enabled=true
Enter fullscreen mode Exit fullscreen mode

Using the Feature Flags

  • Now, let's say we have a DemoService in which we want to use the FeatureAFeatureFlag we just created. We will use it like this:
@Service
public class DemoServiceImpl implements DemoService {
  @Override
  @FeatureFlag(validators = {FeatureAFeatureFlag.class})
  public String featureA() {
    return "Hello from A";
  }
}
Enter fullscreen mode Exit fullscreen mode

Since, we have annotated our method with the FeatureFlag annotation and used the FeatureAFeatureFlag class in it, so before executing the method featureA, FeatureAFeatureFlag will be executed and it will check whether the feature is enabled or not.

Note:

Note here, validators field is an array in the FeatureFlag annotation, hence we can pass multiple validators to it.

Using the Feature Flags in Controller

  • In the previous example, we applied the FeatureAFeatureFlag around a service layer method. However, feature flags can also be applied to controller methods. This allows us to inspect input parameters and, based on specific conditions, control whether the user can proceed with the requested flow.
  • Let’s consider a Feature B, which has a controller method accepting a request parameter flowType. Currently, Feature B only supports the INWARD flow, while other flows are being tested for future rollout. In this case, we’ll create a feature flag for Feature B that checks whether the flowType is INWARD and ensures that only this flow is allowed for now.

To implement the feature flag for Feature B, we would have to update the FeatureFlagConfigsand application.properties files accordingly.

@RequiredArgsConstructor
@ConfigurationProperties(prefix = "feature-flags")
@Getter
public class FeatureFlagConfigs {
  final Boolean featureAEnabled;
  final Boolean featureBEnabled;
  final String featureBEnabledFlowTypeValues;
}
Enter fullscreen mode Exit fullscreen mode
# Feature Flags Configurations (application.properties)
feature-flags.feature-a-enabled=false
feature-flags.feature-b-enabled=true
feature-flags.feature-b-enabled-flow-type-values=INWARD
Enter fullscreen mode Exit fullscreen mode
  • Now, we will create a FeatureBFeatureFlag class. The FeatureBFeatureFlag class will validate if Feature B is enabled and whether the flowType matches the allowed value (INWARD). If these conditions aren't met, the feature will be disabled.
@Component
@RequiredArgsConstructor
public class FeatureBFeatureFlag implements FeatureFlagValidator {
  private final FeatureFlagConfigs featureFlagConfigs;
  private final Logger logger = LoggerFactory.getLogger(FeatureBFeatureFlag.class);
  private final HttpServletRequest httpServletRequest;

  @Override
  public boolean validate(Object... args) {
    boolean enabled = featureFlagConfigs.getFeatureBEnabled();
    String flowType = httpServletRequest.getParameter("flowType");
    boolean isFlowAllowed =
        Arrays.stream(featureFlagConfigs.getFeatureBEnabledFlowTypeValues().split(","))
            .toList()
            .contains(flowType);
    if (!(isFlowAllowed && enabled)) {
      logger.error("Feature B is not enabled!");
    }
    return isFlowAllowed && enabled;
  }
}
Enter fullscreen mode Exit fullscreen mode

We will use the above feature flag with the controller like this:

@RestController
@RequestMapping("/demo")
@RequiredArgsConstructor
public class DemoController {

  private final DemoService demoService;

  @GetMapping("/a")
  public ResponseEntity<String> featureA() {
    String result = demoService.featureA();
    return ResponseEntity.ok(result);
  }

  @GetMapping("/b")
  @FeatureFlag(validators = {FeatureBFeatureFlag.class})
  public ResponseEntity<String> featureB(@RequestParam String flowType) {
    String result = demoService.featureB(flowType);
    return ResponseEntity.ok(result);
  }
}
Enter fullscreen mode Exit fullscreen mode

In this way, we can create our custom feature flags in Spring Boot. We have created feature flags in such a way that they can be extended and we can add multiple ways of toggling the features. The approach above can also be modified and inside the feature flag validators, we can use a database table as well to toggle features. This table can be managed using an Admin Panel.

If you have made it this far, I wholeheartedly thank you for your time. I hope you found this article worth the investment. Your feedback is much appreciated. Thank you! Happy learning!

Top comments (0)