Explain IoC and dependency injection in Spring. How does Spring decide which bean to inject?
Inversion of Control
Objects do not create their dependencies; a container creates objects (beans), wires them together and manages their lifecycle. Code depends on abstractions, and configuration decides the implementation. This makes classes easier to test (inject a fake) and to change.
ApplicationContext vs BeanFactory
BeanFactory is the basic container (lazy instantiation, DI). ApplicationContext builds on it with eager singleton creation (so configuration errors fail at startup), events, internationalisation, environment and profiles, AOP integration and automatic registration of BeanPostProcessors. Applications always use an ApplicationContext.
Injection styles
- Constructor injection (preferred): dependencies are explicit and can be
final; the object is never half-built; easy to unit test without Spring; circular dependencies fail fast. With one constructor,@Autowiredis optional. - Setter injection: for genuinely optional dependencies.
- Field injection: concise but hides dependencies, prevents
final, and requires reflection or Spring in tests. Avoid in production code.
Resolution rules
- Spring resolves by type.
- If several beans match: a bean marked
@Primarywins; otherwise a@Qualifier("name")on the injection point selects one; otherwise the parameter name is matched against bean names. - Still ambiguous →
NoUniqueBeanDefinitionExceptionat startup. - Injecting
List<T>orMap<String, T>gives you all beans of that type (ordered by@Order), which is the basis of plugin-style strategies. Optional<T>orObjectProvider<T>for optional or lazily resolved dependencies.
Example
@Service
public class CheckoutService {
private final PaymentGateway gateway;
private final Map<String, ShippingCalculator> calculators; // bean name -> implementation
public CheckoutService(@Qualifier("stripeGateway") PaymentGateway gateway,
Map<String, ShippingCalculator> calculators) {
this.gateway = gateway;
this.calculators = calculators;
}
}Follow-up questions interviewers ask
Try answering each one before you open it.
How does Spring handle circular dependencies?
With constructor injection it cannot (A needs B to be constructed and B needs A), so it fails at startup with BeanCurrentlyInCreationException. Historically it resolved setter and field cycles by exposing an "early reference" through its three-level singleton cache. Since Spring Boot 2.6 circular references are prohibited by default (spring.main.allow-circular-references=false). The right fix is design: extract the shared logic into a third bean, or use events. @Lazy on one side is a workaround that injects a proxy.
What is the difference between @Component, @Service, @Repository and @Bean?
@Component marks a class for component scanning; @Service and @Repository are specialisations that document intent, and @Repository additionally enables translation of persistence exceptions into Spring's DataAccessException hierarchy. @Bean is placed on a method in a @Configuration class and is used when you cannot annotate the class (third-party types) or need custom construction logic.