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
.