Repaso
EspaƱol

Which injection style is generally recommended in Spring?

Options

  1. Field injection with @Autowired on fields
  2. Constructor injection with final fields (Correct option)
  3. Setter injection on every optional bean
  4. 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 new and 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.

Key terms

Practice this question in Repaso