Member-only story
Is Autowired Annotation Deprecated in Spring Boot? Everything You Need to Know
No, @Autowired
is not deprecated in Spring Boot! However, it has been optional since Spring 4.3. Learn why constructor injection is now the preferred approach and when you still need @Autowired
.
📌 Is @Autowired
Deprecated in Spring Boot?
No, @Autowired
is NOT deprecated in Spring or Spring Boot. However, since Spring 4.3, it has been made optional if a class has only one constructor.
With Spring Boot 3+, the best practice is to use constructor injection without @Autowired
, as Spring automatically injects dependencies when a bean has only one constructor.
🔹 What is @Autowired
?
The @Autowired
annotation is used in Spring to enable automatic dependency injection. It allows Spring to inject the required dependencies into a class automatically, without requiring manual object creation.
✅ Example: Using @Autowired
to Inject Dependencies
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
public List<Product> getAllProducts() {
return productRepository.findAll();
}
}
💡 This tells Spring to automatically inject an instance of ProductRepository
into ProductService
.
📌 Why is @Autowired
Optional in Spring Boot 3+?
Since Spring 4.3, @Autowired
is not needed when using constructor-based injection, provided that there is only one constructor in the class.
✅ How Spring Automatically Injects Dependencies
If a class has a single constructor, Spring automatically injects dependencies without requiring @Autowired
.
🚨 Before (Using @Autowired
)
@Service
public class ProductService {
private final ProductRepository productRepository;
@Autowired // Not needed in Spring Boot 3+
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
}
✅ After (Best Practice)
@Service
public class ProductService…