@Service
public class OrderService {
private final PaymentService paymentService;
// Constructor injection — the recommended approach
public OrderService(PaymentService paymentService) {
this.paymentService = paymentService;
}
}- Constructor injection — preferred; makes dependencies explicit and final
- Field injection (@Autowired on a field) — concise but harder to unit test
- Setter injection — used for optional dependencies
Tip
Always recommend constructor injection when asked — it's the current best practice and enables immutability.