π― 10 Tricky Spring Boot Bean Creation Interview Questions (With Answers)
Knowing how Spring Boot manages beans is critical for backend interviews. Here's a curated list of tricky but real-world interview questions, each with a sharp, confident answer you can use in your blog or interviews.
β
1. How many instances of a @Component
bean are created by default in Spring Boot?
βοΈ Answer:
Only one instance is created per Spring container. This is due to the default singleton scope in Spring.
Bonus: You can verify this by comparing two injected references or printing the bean hashcode.
β 2. How do you create a new object of a bean every time it's needed?
βοΈ Answer:
Use the @Scope("prototype")
annotation:
Now Spring will create a new instance every time the bean is requested.
β
3. Can you use @Autowired
with prototype-scoped beans?
βοΈ Answer:
Yes, but be careful!
-
If injected directly via
@Autowired
, Spring injects only once (at startup). -
To get a new object every time, use
ObjectFactory
orProvider
:
β 4. How does Spring Boot know which beans to create?
βοΈ Answer:
Spring Boot uses @ComponentScan
(inside @SpringBootApplication
) to automatically detect classes annotated with:
-
@Component
-
@Service
-
@Repository
-
@Controller
β 5. How to find out how many beans Spring has created at startup?
βοΈ Answer:
In your main class:
β 6. Can you have multiple beans of the same type? How does Spring know which one to inject?
βοΈ Answer:
Yes, and you can resolve conflicts using:
-
@Primary
β Marks a bean as default -
@Qualifier("beanName")
β Specifies the exact bean to inject
β 7. What happens if two beans implement the same interface and no qualifier is used?
βοΈ Answer:
Spring throws a NoUniqueBeanDefinitionException
, because it doesn't know which bean to inject.
β
8. Whatβs the difference between @Bean
and @Component
?
βοΈ Answer:
@Component | @Bean |
---|---|
Used on classes | Used on methods inside @Configuration |
Automatically discovered | Explicitly declared |
Can't customize easily | Fine-grained control of object creation |
β 9. How do you define a lazy-loaded bean?
βοΈ Answer:
Use @Lazy
:
Now Spring creates the bean only when itβs first requested, not at startup.
β
10. Can Spring Boot manage third-party objects (e.g., not annotated with @Component
)?
βοΈ Answer:
Yes! Register them using @Bean
:
Spring will manage the lifecycle just like any other bean.
π§ Bonus Tip: Must-Know Keywords for Interviews
"Spring Boot scans for beans using annotations like @Component. By default, it uses singleton scope, but we can switch to prototype or request. The container handles bean lifecycle and dependency resolution using IoC and DI principles."