Sobes.tech
Junior — Middle

What is the reason for using @Autowired annotation directly on a field instead of applying it on a constructor?

sobes.tech AI

Answer from AI

Using the @Autowired annotation directly on a field (field injection) instead of a constructor is often associated with simplicity and convenience, especially in small classes or during rapid prototyping.

Reasons:

  • Allows quick dependency injection without the need to write a constructor.
  • Simplifies code when a class has many dependencies, making the constructor bulky.

However, this approach has disadvantages: it is harder to write tests because dependencies are implicit, and it violates the principle of dependency inversion.

Overall, @Autowired on a field is used for convenience, but constructor injection is recommended for better testability and explicit dependencies.