Spring Boot中构造方法的@Autowired注解是否必填?构造函数DI需加吗?
Great question — this is a super common point of confusion when working with constructor-based dependency injection in Spring Boot. Let's break it down with clear rules and examples:
Core Rule (Spring 4.3+)
Starting from Spring Framework 4.3, the @Autowired annotation on a constructor is optional in most cases. Spring will automatically detect and use a constructor for dependency injection based on how many constructors your class has.
Case 1: Class has only one constructor
If your bean class (marked with @Component, @Service, @Repository, etc.) has exactly one constructor, Spring will automatically use it to inject dependencies—no @Autowired needed at all. This applies even if the constructor has multiple parameters that are Spring-managed beans.
Example:
@Service public class UserService { private final UserRepository userRepo; // No @Autowired required here! public UserService(UserRepository userRepo) { this.userRepo = userRepo; } }
Case 2: Class has multiple constructors
If your class has more than one constructor, you must add @Autowired to the constructor you want Spring to use for dependency injection. Without this annotation, Spring won't know which constructor to pick and will throw an exception at startup.
Example:
@Service public class OrderService { private final OrderRepository orderRepo; private final NotificationService notificationService; // This constructor will be used by Spring (thanks to @Autowired) @Autowired public OrderService(OrderRepository orderRepo, NotificationService notificationService) { this.orderRepo = orderRepo; this.notificationService = notificationService; } // This constructor won't be used by Spring unless you add @Autowired to it public OrderService(OrderRepository orderRepo) { this.orderRepo = orderRepo; this.notificationService = new NotificationService(); // Manual instantiation } }
Additional Notes
- This rule also applies to beans created via
@Configurationclasses (using@Beanmethods). If the bean class has a single constructor, you don't need@Autowiredwhen defining the bean. - Omitting
@Autowiredfor single constructors is generally recommended—it keeps your code cleaner and aligns with modern Spring best practices.
内容的提问来源于stack exchange,提问作者Vitalii




