@Autowired kích hoạt tự động inject dependency — Spring tự resolve và inject bean phù hợp.
Đặt được trên: constructor, setter, field.
Resolution mặc định: by type. Nếu nhiều bean cùng type → ambiguity, fix bằng @Qualifier("beanName") hoặc @Primary.
@Service
class OrderService {
// Spring 4.3+: constructor duy nhất không cần @Autowired
private final UserRepository repo;
public OrderService(UserRepository repo) { this.repo = repo; }
}
// Khi có nhiều bean cùng type
@Service
class NotificationService {
public NotificationService(@Qualifier("smtp") MailSender sender) {}
}
// Optional dependency
@Autowired(required = false)
private Cache cache;Quy tắc 2026:
- ✅ Constructor injection — rõ ràng, final, dễ test.
- ❌ Field injection — hidden dependency, cần reflection để mock.
- Setter injection cho optional dependency.
Lombok @RequiredArgsConstructor giúp viết constructor injection gọn — tự sinh constructor cho final field.
@Autowired enables automatic dependency injection — Spring resolves and injects the right bean.
Can be placed on: constructors, setters, fields.
Default resolution: by type. Multiple beans of the same type → ambiguity, fix with @Qualifier("beanName") or @Primary.
@Service
class OrderService {
// Spring 4.3+: a single constructor needs no @Autowired
private final UserRepository repo;
public OrderService(UserRepository repo) { this.repo = repo; }
}
// When multiple beans of the same type exist
@Service
class NotificationService {
public NotificationService(@Qualifier("smtp") MailSender sender) {}
}
// Optional dependency
@Autowired(required = false)
private Cache cache;2026 rules:
- ✅ Constructor injection — explicit, final, test-friendly.
- ❌ Field injection — hidden dependency, requires reflection to mock.
- Setter injection for optional dependencies.
Lombok's @RequiredArgsConstructor makes constructor injection concise — generates a constructor for final fields.