| Constructor | Setter | Field | |
|---|---|---|---|
| Immutability | Có — final | Không | Không — |
| Mandatory dep | Có — Rõ ràng | Không — Optional mặc định | Không |
| Testability | Có — Tốt nhất | Có — Tốt | Hạn chế — 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.