java 45 lines · 7 steps

A custom @Conditional feature flag in Spring

A Spring Condition that toggles bean registration based on a feature flag property and active profiles.

Explained by highlit
1package com.example.config.condition;
2 
3import org.springframework.context.annotation.Condition;
4import org.springframework.context.annotation.ConditionContext;
5import org.springframework.core.env.Environment;
6import org.springframework.core.type.AnnotatedTypeMetadata;
7 
8import java.util.Map;
9 
10public class OnFeatureFlagCondition implements Condition {
11 
12 @Override
13 public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
14 Map<String, Object> attributes =
15 metadata.getAnnotationAttributes(ConditionalOnFeature.class.getName());
16 if (attributes == null) {
17 return false;
18 }
19 
20 String feature = (String) attributes.get("value");
21 boolean expected = (boolean) attributes.get("enabledByDefault");
22 
23 Environment env = context.getEnvironment();
24 String property = "features." + feature + ".enabled";
25 boolean enabled = env.getProperty(property, Boolean.class, expected);
26 
27 String[] requiredProfiles = (String[]) attributes.get("activeProfiles");
28 if (requiredProfiles.length > 0 && !anyProfileActive(env, requiredProfiles)) {
29 return false;
30 }
31 
32 return enabled;
33 }
34 
35 private boolean anyProfileActive(Environment env, String[] profiles) {
36 for (String profile : profiles) {
37 for (String active : env.getActiveProfiles()) {
38 if (active.equalsIgnoreCase(profile)) {
39 return true;
40 }
41 }
42 }
43 return false;
44 }
45}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Implementing Condition lets you gate bean registration on arbitrary runtime logic beyond Spring's built-in conditions.
  2. 2Reading annotation attributes via AnnotatedTypeMetadata connects a custom annotation to its evaluation logic.
  3. 3Combining a property lookup with a profile check produces flexible, layered activation rules.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A custom @Conditional feature flag in Spring — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code