Bird
0
0

Why does this custom auto-configuration fail to create a bean?

medium📝 Debug Q7 of 15
Spring Boot - Advanced Patterns
Why does this custom auto-configuration fail to create a bean?
@Configuration
public class MyAutoConfig {
  @Bean
  private MyService myService() {
    return new MyService();
  }
}
AClass must be annotated with @Component instead
BBean methods must be public, private is invalid
CMissing @ConditionalOnMissingBean annotation
DMyService class is not annotated with @Service
Step-by-Step Solution
Solution:
  1. Step 1: Check bean method visibility

    Spring requires @Bean methods to be public to detect and invoke them.
  2. Step 2: Evaluate other options

    @ConditionalOnMissingBean is optional. @Component is not for config classes. @Service on MyService is unrelated to bean creation here.
  3. Final Answer:

    Bean methods must be public, private is invalid -> Option B
  4. Quick Check:

    @Bean methods must be public [OK]
Quick Trick: Make @Bean methods public to be detected by Spring [OK]
Common Mistakes:
  • Using private or protected bean methods
  • Confusing @Component with @Configuration
  • Expecting @Service on bean class to matter here

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes