DI: dependency được cung cấp từ bên ngoài thay vì object tự tạo → giảm coupling, tăng testability (mock được).
Không có DI:
class UserService {
private final UserRepository repo = new UserRepository(); // ❌ tight coupling
}Có DI:
class UserService {
private final UserRepository repo;
public UserService(UserRepository repo) { this.repo = repo; } // inject từ ngoài
}3 cách inject trong Spring:
1. Constructor injection — KHUYẾN NGHỊ. Immutable (final), required dependency rõ ràng, dễ test:
@Service
class UserService {
private final UserRepository repo;
public UserService(UserRepository repo) { this.repo = repo; }
}Spring 4.3+: 1 constructor → không cần @Autowired.
2. Setter injection — cho optional dependency: void setLogger(Logger l).
3. Field injection — @Autowired UserRepository repo; — đơn giản nhưng anti-pattern: khó test (cần reflection để mock), không thấy dependency trong constructor.
IoC container (ApplicationContext) quản lý lifecycle bean + wiring tự động qua component scan.
DI: dependencies are supplied from outside instead of objects creating them → reduces coupling, improves testability (mockable).
Without DI:
class UserService {
private final UserRepository repo = new UserRepository(); // ❌ tight coupling
}With DI:
class UserService {
private final UserRepository repo;
public UserService(UserRepository repo) { this.repo = repo; } // injected externally
}Three injection styles in Spring:
1. Constructor injection — RECOMMENDED. Immutable (final), required dependencies are explicit, easy to test:
@Service
class UserService {
private final UserRepository repo;
public UserService(UserRepository repo) { this.repo = repo; }
}Spring 4.3+: a single constructor needs no @Autowired.
2. Setter injection — for optional dependencies: void setLogger(Logger l).
3. Field injection — @Autowired UserRepository repo; — simple but an anti-pattern: hard to test (reflection needed to mock), dependencies hidden from the constructor.
The IoC container (ApplicationContext) manages bean lifecycle + auto-wires through component scanning.