Skip to the page

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.

The 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 call new 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 @RequiredArgsConstructor with private final fields 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 inject Map<String, PaymentGateway> or List<PaymentGateway> and pick one (a strategy). To see the beans: the /actuator/beans endpoint when exposed, or ApplicationContext.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

  1. What does the Spring container do at startup? What is a bean?
  2. BeanFactory or ApplicationContext?
  3. Constructor or field injection? Why?
  4. The app stopped starting after a second PaymentGateway class was added. Why and how do you fix it?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview