Bird
0
0

You want to create two beans of the same type but only one should be active based on a property mode which can be "simple" or "advanced".

hard📝 Application Q15 of 15
Spring Boot - Advanced Patterns
You want to create two beans of the same type but only one should be active based on a property mode which can be "simple" or "advanced".
Which is the best way to define these beans using @ConditionalOnProperty?
AUse <code>@ConditionalOnProperty(name = "mode", havingValue = "simple")</code> on the simple bean and <code>@ConditionalOnProperty(name = "mode", havingValue = "advanced")</code> on the advanced bean
BUse <code>@ConditionalOnProperty(name = "mode")</code> on both beans without havingValue
CCreate both beans without conditions and select one at runtime
DUse <code>@ConditionalOnProperty(name = "mode", matchIfMissing = true)</code> on both beans
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    Only one bean should be active depending on the property value "simple" or "advanced".
  2. Step 2: Apply conditional annotations

    Using @ConditionalOnProperty with havingValue set to "simple" or "advanced" on each bean ensures only one bean loads.
  3. Step 3: Evaluate other options

    Use @ConditionalOnProperty(name = "mode") on both beans without havingValue lacks value check, so both beans may load; Create both beans without conditions and select one at runtime loads both always; Use @ConditionalOnProperty(name = "mode", matchIfMissing = true) on both beans activates both if property missing.
  4. Final Answer:

    Use @ConditionalOnProperty(name = "mode", havingValue = "simple") on the simple bean and @ConditionalOnProperty(name = "mode", havingValue = "advanced") on the advanced bean -> Option A
  5. Quick Check:

    Use havingValue to select one bean by property [OK]
Quick Trick: Use havingValue to pick one bean per property value [OK]
Common Mistakes:
  • Not specifying havingValue causing both beans to load
  • Trying to select bean at runtime instead of conditionally
  • Using matchIfMissing on both beans causing conflicts

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes