Why You Should Avoid Using @Autowired in Spring Applications

Saurav Kumar
3 min readDec 14, 2024

In the Spring ecosystem, dependency injection is a key concept that allows for cleaner and more maintainable code. Among the various ways to inject dependencies, @Autowired has been widely used. However, while convenient, @Autowired has its drawbacks. In this blog, I’ll explain why @Autowired should be avoided and provide a proof-of-concept to demonstrate a better alternative: constructor injection.

Understanding @Autowired

@Autowired is an annotation that automatically injects a dependency into a Spring-managed bean. While it simplifies dependency injection, it comes with limitations that can impact your codebase’s maintainability, testability, and clarity.

Why Avoid @Autowired?

Here are the major reasons to avoid @Autowired:

  1. Hidden Dependencies Dependencies injected via @Autowired are not visible in the constructor or method signature, making it difficult to understand the requirements of a class.
  2. Null Pointer Exceptions If Spring fails to inject a bean (e.g., due to misconfiguration), @Autowired can lead to a runtime NullPointerException.
  3. Reduced Testability Testing components with @Autowired often requires initializing the entire Spring context, which slows…

--

--

Saurav Kumar
Saurav Kumar

Written by Saurav Kumar

Experienced Software Engineer adept in Java, Spring Boot, Microservices, Kafka & Azure.

No responses yet