DIGITAL GURU
Java Roadmap Portfolio

Constructor Injection (Step-by-Step Guide)

Why Constructor Injection is the #1 recommended best practice in Java & Spring Boot.

Anuj Kumar Singh Written by Anuj Kumar Singh (Lead Engineer, 13+ yrs exp) 5 min read Verified Spring Boot 3+ Guide
3D Architecture Visualizer

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 final so 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:

OrderService.java
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:

  1. @Service: Tells Spring IoC container: "Hey Spring, please create this bean for me and store it in your container."
  2. private final PaymentRepository paymentRepository;: The final keyword guarantees that once set, paymentRepository can never be changed or set to null.
  3. public OrderService(PaymentRepository paymentRepository): Spring automatically finds the PaymentRepository bean 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!