Spring boot allows you to create components conditionally, already seen condition is profile condition. You can just say @Profile(“dev”) and have different implementation of the bean.
What if you want to configure some especial condition, like enable or disable a feature? Here the @Conditional comes to play.
We want to create a service only if feature is configured to be enabled. Enabled status of the feature is specified using especial property in application.properties
1 |
rs.pscode.firebase.enabled=true |
To accomplish this we need to do 3 things
- Create Condition Implementation
- Create Condition Annotation
- Annotate the Class
Condition implementation is super simple, you just implement Condition interface and return true or false. Here I check if property is set to true.
1 2 3 4 5 6 7 8 9 10 11 12 |
import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; public class FirebaseConditionImpl implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { String enabled = context.getEnvironment().getProperty("rs.pscode.firebase.enabled"); return Boolean.parseBoolean(enabled); } } |
Custom annotation that is annotated by especial annotation @Conditional with value set to condition implementation
1 2 3 4 5 6 |
@Target(value = ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Conditional(value = FirebaseConditionImpl.class) public @interface FirebaseCondition { } |
Using FirebaseCondition I annotate my service that depends on this condition
1 2 3 4 5 6 7 8 |
@Service @FirebaseCondition public class FirebaseServiceImpl implements FirebaseService { @Override public FirebaseTokenHolder parseToken(String firebaseToken) { return new FirebaseParser().parseToken(firebaseToken); } } |
This is it! Now FirebaseService will be wired only when application.property is correctly filled.