Spring Dependency Injection: Wiring Styles, Scopes and Cycles
System DesignModel answerLast 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
ApplicationContextdo to find, create and connect beans? - Where does injection happen relative to initialization callbacks such as
@PostConstructandInitializingBean?
2. Constructor vs. setter vs. field injection
Compare the three styles on:
- required vs. optional dependencies
- immutability (
finalfields) - unit testing without booting a Spring context
- protection against
NullPointerExceptioncaused 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
singletonandprototypescopes. - 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 -> BeanAarise, 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.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Summary of the position
Make constructor injection the default, keep singleton beans stateless, disambiguate multiple candidates explicitly, and treat any circular dependency as a design bug to fix, not hide.
1. Container and lifecycle
The ApplicationContext owns object creation, so your classes declare what they need and the container supplies it. That is inversion of control. During refresh() it roughly does the following:
- Collect bean definitions from component scanning (
@Component,@Service,@Repository),@Configurationclasses with@Beanmethods, and auto-configuration. At this point there are only metadata records (class, scope, dependencies), not objects. - Run
BeanFactoryPostProcessors (for example, property placeholder resolution) and registerBeanPostProcessors. - Instantiate each non-lazy singleton. Constructor injection occurs here, because the container must have the arguments to call the constructor.
- Populate properties. Setter and field injection occur here, driven by the
@Autowiredpost-processor. - Aware callbacks such as
BeanNameAware. - Initialization:
@PostConstruct(a before-init post-processor), thenInitializingBean.afterPropertiesSet(), then a custominitMethod. - After-init post-processing, where AOP proxies for
@Transactional,@Asyncand similar are created. - Shutdown:
@PreDestroyandDisposableBean.destroy().
The takeaway is that all injection completes before any init hook. Dependencies are safe to use in @PostConstruct, but with field or setter injection they are still null inside the constructor.
2. Injection styles
@Service
public class TransferService {
private final AccountRepository accounts;
private final AuditSink audit;
public TransferService(AccountRepository accounts, AuditSink audit) {
this.accounts = accounts;
this.audit = audit;
}
}
With a single constructor, @Autowired is optional (Spring 4.3+).
| Criterion | Constructor | Setter | Field |
|---|---|---|---|
| Required vs. optional | Mandatory by signature; optional ones via ObjectProvider or Optional | Good for optional or re-settable collaborators | required=false possible, but the contract is invisible |
| Immutability | final fields | Not possible | Not possible |
| Plain unit test | new TransferService(repoMock, auditMock) | Works, but easy to forget a setter | Needs reflection or a Mockito/Spring runner |
| NPE safety | Object is never observable half-built; missing beans fail at startup | Can exist with unset deps | Fields are null during construction and outside Spring |
Recommendation: constructor injection for everything required, setter injection only for truly optional or swappable collaborators, no field injection in production code. A bonus is that a constructor with seven or eight parameters makes a Single Responsibility violation visible, whereas field injection hides it behind a stack of annotations.
3. Multiple implementations
Injecting by type when two beans match throws NoUniqueBeanDefinitionException. Options:
@Primarymarks the default candidate.@Qualifier("achGateway")at the injection point selects a specific bean and wins over@Primary.- Custom qualifier annotation gives compile-time safety instead of string names:
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD})
public @interface Wire {}
@Service @Wire
class WireGateway implements PaymentGateway { }
PaymentRouter(@Wire PaymentGateway gateway) { }
- Inject a
List<PaymentGateway>orMap<String, PaymentGateway>when the choice is made at runtime. This is a natural strategy-pattern setup, for example choosing a gateway by payment type.
Spring can also fall back to matching a parameter name to a bean name. This breaks silently on rename, so do not depend on it.
4. Scopes and thread safety
singleton(default): one shared instance per container, created at startup.prototype: a new instance per injection or lookup. Spring does not run destruction callbacks for it.- Web scopes (
request,session) exist for per-request or per-user state.
A servlet container handles requests on a thread pool, and every thread calls the same singleton. A mutable field is therefore a data race:
@Service
class FeeCalculator {
private BigDecimal runningTotal; // shared by every request: bug
}
In a payments system this means wrong totals or one customer's data appearing in another's response.
Stateless design rules:
- Hold only
finalreferences to other stateless collaborators. - Carry request data in method parameters and local variables.
- Put real state in the database, a cache, or request-scoped objects.
- If shared in-memory state is unavoidable, use immutable objects,
ConcurrentHashMap, or atomics. - Clear any
ThreadLocalin afinallyblock, since pooled threads are reused.
Common pitfall: a prototype injected into a singleton is resolved once, at singleton creation, so it effectively behaves like a singleton. Inject an ObjectProvider<T> (or use a scoped proxy) to get a fresh instance each time.
5. Circular dependencies
Cause: A needs B and B needs A. With constructor injection neither can be built first, so startup fails with BeanCurrentlyInCreationException. With setter or field injection, Spring has historically been able to expose an early reference to a partially built bean to break the loop. That hides the problem and can leak an unproxied object where a proxy was expected. Recent Spring Boot versions disable circular references by default.
What it usually signals:
- Responsibilities split along the wrong boundary (an SRP issue).
- Layer violations, such as a service depending on a web-layer component.
- Two classes that are really one concept, or shared logic that belongs in neither.
Structural fixes:
- Extract a third component. If
AccountServiceandTransferServiceboth need balance checks, move that into aBalanceValidatorthat both depend on. - Invert one edge with events.
Apublishes an event andBlistens, soAno longer knowsB. - Depend on a narrow interface owned by the lower layer, so dependencies point one way.
@Lazy injects a proxy and postpones the failure to runtime. It is acceptable as a short-term patch around third-party code, not as a design.
Common mistakes to avoid
- Claiming constructor injection is "faster" instead of arguing from safety and testability.
- Using
@Qualifierand@Primaryinterchangeably without noting that the qualifier is more specific. - Believing
prototypebeans are refreshed on every call when injected into singletons. - Thinking
synchronizedeverywhere is the fix for singleton state, when the better fix is removing the state.