Interview kitsBlog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2026 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Spring
Springeasy

What is Dependency Injection in Spring and why prefer constructor injection?

Tags
#di#ioc#constructor-injection
Back to categoryPractice quiz

Answer

Spring creates objects (beans) and injects their dependencies, so code depends on abstractions, not manual wiring. Constructor injection makes dependencies explicit, supports immutability (`final`), and is easiest to test.

@Service
class UserService {
  private final UserRepository repo;

  UserService(UserRepository repo) {
    this.repo = repo;
  }
}

Advanced answer

Deep dive

Dependency Injection (DI) is a pattern where an external container (Spring) constructs objects and provides their dependencies. In Spring, this is handled by the IoC container (ApplicationContext): it instantiates beans, resolves wiring, manages lifecycle, and applies cross‑cutting features (AOP, transactions, security).

Constructor injection is preferred because:

  • **Dependencies are explicit**: if it compiles, required dependencies are provided.
  • **Immutability**: fields can be `final` and safely initialized once.
  • **Testability**: you can `new` the class in unit tests without Spring.
  • **Fail fast**: missing beans fail at startup, not at runtime.

Practical patterns

  • Use constructor injection for required dependencies.
  • For optional dependencies, prefer `Optional<T>` / `ObjectProvider<T>` or split responsibilities.
  • Watch constructor size: many dependencies often indicates a class doing too much.

Example

@Service
class UserService {
  private final UserRepository repo;
  private final Clock clock;

  UserService(UserRepository repo, Clock clock) {
    this.repo = repo;
    this.clock = clock;
  }
}

Common pitfalls

Related questions

Spring
BeanFactory vs ApplicationContext: what’s the practical difference?
#spring#ioc#applicationcontext
Spring
`@Qualifier` vs `@Primary`: how do they resolve multiple beans?
#spring#di#qualifier
Spring
What is the Spring `ApplicationContext` (in one sentence)?
#spring#ioc
  • Field injection hides dependencies and complicates testing.
  • Circular dependencies are harder with constructors (good: it exposes design problems early).
  • Mixing manual `new` with Spring-managed beans (you lose proxies and lifecycle features).
  • #applicationcontext
    Spring
    What is Dependency Injection?
    #di#inversion-of-control#spring