Spring Boot core · core
The container, beans and dependency injection
The Spring container creates objects called beans and passes in what they need. Use constructor injection. When two beans have the same type, Spring does not guess: you choose.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Inversion of control: your classes do not build their own dependencies. The container builds the beans and passes them in. Dependency injection is how: through the constructor (preferred), a setter or a field.
- At startup the container reads configuration: component scanning of @Component, @Service, @Repository and @Controller classes, and @Bean methods in @Configuration classes.
- ApplicationContext is the full container: BeanFactory plus events, profiles, the Environment, messages and eager creation of singletons.
@SpringBootApplication=@SpringBootConfiguration+@EnableAutoConfiguration+@ComponentScan(from the main class's package down).- Constructor injection: dependencies can be
final, the object is never half-built, and a plain unit test can callnew OrderService(fakeRepo, fixedClock). Field injection hides what the class needs and leaves nulls outside Spring. - Many constructor parameters is a design smell: the class does too much. Lombok's
@RequiredArgsConstructorwithprivate finalfields is the usual short form. - Circular references fail at startup by default since Spring Boot 2.6. Fix the design, for example with a third bean for the shared logic.
- Two beans of one type: startup fails with
NoUniqueBeanDefinitionException. Fix with@Primary,@Qualifier("upiGateway"), or injectMap<String, PaymentGateway>orList<PaymentGateway>and pick one (a strategy). To see the beans: the/actuator/beansendpoint when exposed, orApplicationContext.getBeanDefinitionNames().
The red pen
Common traps: mistake → fix
Mistake: @Autowired on fields is the same as constructor injection
Fix: fields cannot be final and are hard to test without Spring.
Mistake: Spring picks the right bean by name when types clash
Fix: it fails at startup unless you use @Primary or @Qualifier.
Mistake: Circular dependencies can be turned off with a property
Fix: the property hides a design problem.
Easy to hard
Questions interviewers ask, easy to hard
- What does the Spring container do at startup? What is a bean?
- BeanFactory or ApplicationContext?
- Constructor or field injection? Why?
- The app stopped starting after a second PaymentGateway class was added. Why and how do you fix it?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.