Spring Boot FAQ: Top Questions
46. What is the use of @Conditional annotation in Spring Boot?
@Conditional
is used to conditionally register a Spring bean depending on the result of a specified condition.
πΊοΈ Steps:
- Define a class implementing
Condition
. - Annotate bean method or class with
@Conditional(MyCondition.class)
.
π₯ Example:
public class OnWindowsCondition implements Condition {
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return System.getProperty("os.name").contains("Windows");
}
}
π Expected Output:
Bean is registered only on Windows OS.
π οΈ Use Cases:
- Load beans based on environment, classpath, or property.
- Enable/disable configuration features conditionally.