KatInterview

Spring Dependency Injection: Wiring Styles, Scopes and Cycles

System DesignModel answer
EasyModel answerSystem Designspringdependency-injectionioc

Last updated

Explain how Spring's container wires beans, compare constructor, setter and field injection, resolve ambiguous beans, reason about scope and thread safety, and untangle circular dependencies.

Context

Your team is writing a coding standard for a set of Spring-based payment microservices. You have been asked to explain the dependency injection model behind the standard and defend the injection style you would mandate.

Prepare a structured answer that covers the five areas below.

1. The container and the bean lifecycle

  • What does the ApplicationContext do to find, create and connect beans?
  • Where does injection happen relative to initialization callbacks such as @PostConstruct and InitializingBean?

2. Constructor vs. setter vs. field injection

Compare the three styles on:

  • required vs. optional dependencies
  • immutability (final fields)
  • unit testing without booting a Spring context
  • protection against NullPointerException caused by half-built objects

State which style you would make the default and why.

3. Several candidates for one type

Suppose an interface such as PaymentGateway or AuditSink has more than one bean. How do you control which one is injected using @Primary, @Qualifier, or a custom qualifier annotation? Is there a way to use all of them?

4. Scopes and thread safety

  • Contrast singleton and prototype scopes.
  • Why is mutable instance state in a singleton dangerous, and how do you design services to avoid it?

5. Circular dependencies

  • How does a cycle such as BeanA -> BeanB -> BeanA arise, and what happens at startup?
  • What design problems does it usually reveal, and how would you fix it structurally rather than reaching for @Lazy?

Use short code snippets where they help.

Hints

Hint 1

Separate the container's work into phases: reading bean definitions, creating instances, populating properties, running init callbacks, and wrapping in proxies. Then ask which phase each injection style belongs to.

Hint 2

For the style comparison, imagine writing `new MyService(...)` in a plain JUnit test, and imagine a mandatory dependency being absent. Which style makes the compiler or the container complain, and which lets the object exist half-initialized?

Hint 3

For singletons, picture many request threads calling the same instance at once. For cycles, ask what a missing 'third concept' or a wrongly drawn layer boundary would look like, and how you could extract or invert one edge.