Real-World Analogy for Beginners
Imagine a Coffee Machine class. A Coffee Machine cannot function without a Water Tank and Coffee Beans. With Constructor Injection, the constructor insists: "You CANNOT build a Coffee Machine unless you hand me the Water Tank and Coffee Beans right when creating it!" This ensures the machine will never crash due to a missing part.
What is Constructor Injection?
In Java, when Class A needs Class B to do its work, Class B is called a Dependency. Constructor Injection means passing Class B into Class A through Class A's constructor method.
Why is Constructor Injection Better Than Other Ways?
- 100% Immutable (Safe): Fields can be marked as
finalso nobody can accidentally overwrite them later. - Prevents NullPointerExceptions: You can never create an object in an incomplete state.
- Easy Unit Testing: You can easily pass fake (mock) objects into the constructor without starting a slow Spring test server.
Complete Beginner Code Example:
package com.anujsingh.digitalguru.service;
import org.springframework.stereotype.Service;
import com.anujsingh.digitalguru.repository.PaymentRepository;
@Service // Tells Spring to create and manage a single instance of this class
public class OrderService {
// Step 1: Declare final dependencies
private final PaymentRepository paymentRepository;
// Step 2: Pass dependency via Constructor
// Note: In Spring 4.3+, if a class has 1 constructor, @Autowired is optional!
public OrderService(PaymentRepository paymentRepository) {
this.paymentRepository = paymentRepository;
}
public void processOrder(double amount) {
System.out.println("Processing order...");
paymentRepository.savePayment(amount);
}
}
Line-by-Line Breakdown:
@Service: Tells Spring IoC container: "Hey Spring, please create this bean for me and store it in your container."private final PaymentRepository paymentRepository;: Thefinalkeyword guarantees that once set,paymentRepositorycan never be changed or set to null.public OrderService(PaymentRepository paymentRepository): Spring automatically finds thePaymentRepositorybean and passes it here!
Common Beginner Mistake
Do not use new PaymentRepository() inside your service class! Let Spring handle object creation automatically. That is the whole power of Dependency Injection!