Which injection style is generally recommended in Spring?
Options
- Field injection with
@Autowiredon fields - Constructor injection with final fields (Correct option)
- Setter injection on every optional bean
- Static fields that are set by the container
Answer
Constructor injection
Why
Constructor injection is preferred because:
- Dependencies can be
final, so the object is always fully built. - It is obvious what a class needs (look at the constructor).
- Unit tests can create the class with
newand pass mocks, without Spring. - Circular dependencies show up immediately.
Field injection hides dependencies and needs reflection or Spring to test. With a single constructor you do not even need @Autowired.
Remember
Prefer constructor injection.