Bird
0
0

How can you create a bean only if no other bean of the same type exists and a specific property service.enabled is set to true?

hard📝 Application Q9 of 15
Spring Boot - Advanced Patterns
How can you create a bean only if no other bean of the same type exists and a specific property service.enabled is set to true?
A@Bean @ConditionalOnMissingBean @ConditionalOnProperty(name = "service.enabled", havingValue = "true") public Service service() { return new Service(); }
B@Bean @ConditionalOnBean(Service.class) @ConditionalOnProperty(name = "service.enabled", havingValue = "true") public Service service() { return new Service(); }
C@Bean @ConditionalOnMissingBean @ConditionalOnProperty(name = "service.enabled", havingValue = "false") public Service service() { return new Service(); }
D@Bean @ConditionalOnClass(Service.class) @ConditionalOnProperty(name = "service.enabled") public Service service() { return new Service(); }
Step-by-Step Solution
Solution:
  1. Step 1: Use @ConditionalOnMissingBean to check bean absence

    This ensures the bean is created only if no other bean of the same type exists.
  2. Step 2: Use @ConditionalOnProperty with havingValue = "true"

    This ensures the bean is created only if the property is set to true.
  3. Step 3: Verify option correctness

    @Bean @ConditionalOnMissingBean @ConditionalOnProperty(name = "service.enabled", havingValue = "true") public Service service() { return new Service(); } correctly combines both conditions. @Bean @ConditionalOnBean(Service.class) @ConditionalOnProperty(name = "service.enabled", havingValue = "true") public Service service() { return new Service(); } requires bean presence, @Bean @ConditionalOnMissingBean @ConditionalOnProperty(name = "service.enabled", havingValue = "false") public Service service() { return new Service(); } checks for false property, @Bean @ConditionalOnClass(Service.class) @ConditionalOnProperty(name = "service.enabled") public Service service() { return new Service(); } checks class presence only.
  4. Final Answer:

    Option A correctly creates bean if missing and property true -> Option A
  5. Quick Check:

    Combine missing bean and property true for conditional creation [OK]
Quick Trick: Use missing bean and property true to create unique conditional bean [OK]
Common Mistakes:
  • Using @ConditionalOnBean instead of missing bean
  • Checking for false property instead of true
  • Confusing class presence with bean presence

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes