Constructor Injection vs. Field Injection: Lessons from a Code Review
Recently, while reviewing a peer’s code, I noticed they had used @AllArgsConstructor instead of the more familiar @Autowired annotation. It sparked a thought: what are the real advantages and drawbacks of constructor injection compared to field injection, and how does this tie into immutability and singleton design?
Why Constructor Injection (@AllArgsConstructor) Can Be Better
Drawbacks of Constructor Injection
Field Injection (@Autowired) in Comparison
Recommended by LinkedIn
The Immutability Challenge in Singleton Beans
In theory, constructor injection promotes immutability. But in practice, immutability isn’t always achievable when:
Example
Even if injected via constructor, CacheService is mutable and shared — immutability is lost.
My Takeaway
Constructor injection (@AllArgsConstructor) is generally the cleaner, safer choice. It enforces dependency visibility and supports immutability. But immutability in Spring applications isn’t automatic — singleton beans and mutable dependencies can still undermine it. The real key is designing dependencies carefully and being mindful of shared state.