| Constructor | Setter | Field | |
|---|---|---|---|
| Immutability | ✅ final | ❌ | ❌ |
| Mandatory dep | ✅ Rõ ràng | ❌ Optional mặc định | ❌ |
| Testability | ✅ Tốt nhất | ✅ Tốt | ⚠ Cần reflection |
| Circular dep | Phát hiện sớm | Có thể bị ẩn | Có thể bị ẩn |
java
@Service
class OrderService {
private final OrderRepository repo; // final → immutable
OrderService(OrderRepository repo) { this.repo = repo; } // Spring 4.3+: 1 constructor khỏi @Autowired
}
// Setter — optional dependency: @Autowired(required = false) void setMetrics(MetricService m) {...}
// Field — KHÔNG khuyến nghị: @Autowired OrderRepository repo; // khó testVì sao constructor injection tốt nhất: final → immutable/thread-safe; bắt buộc dependency → null-safe; test không cần Spring (new OrderService(mock)); circular dependency lộ ngay lúc startup.