in Spring boot

Spring boot conditionals

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

To accomplish this we need to do 3 things

  1. Create Condition Implementation
  2. Create Condition Annotation
  3. 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.

Custom annotation that is annotated by especial annotation @Conditional with value set to condition implementation

Using FirebaseCondition I annotate my service that depends on this condition

This is it! Now FirebaseService will be wired only when application.property is correctly filled.

Write a Comment

Comment