Bird
Raised Fist0
Spring Bootframework~10 mins

Constructor injection (preferred) in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Constructor injection (preferred)
Start Application
↓
Spring creates bean
↓
Identify constructor with dependencies
↓
Inject dependencies via constructor
↓
Bean ready with dependencies
↓
Bean used in application
Spring Boot creates a bean by calling its constructor and passing required dependencies automatically.
Execution Sample
Spring Boot
public class Service {
  private final Repo repo;
  public Service(Repo repo) {
    this.repo = repo;
  }
}
Defines a Service class that receives its Repo dependency through its constructor.
Execution Table
StepActionConstructor CalledDependency InjectedBean State
1Spring starts and scans componentsNoNoNo bean created
2Spring finds Service bean to createNoNoPreparing to create bean
3Spring identifies constructor with Repo parameterYesRepo instanceService bean created with repo
4Service bean ready for useYesRepo instanceBean fully initialized
💡 Bean created after constructor injection completes with all dependencies
Variable Tracker
VariableStartAfter Step 3Final
reponullRepo instance injectedRepo instance injected
Service beannot createdcreated with repoready to use
Key Moments - 2 Insights
Why does Spring call the constructor with parameters instead of using setters?
Spring uses constructor injection to ensure dependencies are provided when the bean is created, as shown in execution_table step 3 where the constructor is called with the Repo instance.
What happens if the required dependency is missing?
Spring will fail to create the bean because it cannot call the constructor without the required dependency, stopping before step 3 in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step does Spring inject the dependency?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Check the 'Dependency Injected' column in the execution_table
According to variable_tracker, what is the value of 'repo' after step 3?
ARepo instance injected
Bnot created
Cnull
DService bean
💡 Hint
Look at the 'repo' row under 'After Step 3' in variable_tracker
If the constructor had no parameters, how would the execution_table change?
ABean would be created with dependencies injected later
BSpring would fail to create the bean
CDependency Injected would be 'No', constructor called with no params
DNo change, same steps
💡 Hint
Think about what happens when constructor has no parameters in execution_table step 3
Concept Snapshot
Constructor injection means passing dependencies via the class constructor.
Spring calls the constructor with required beans automatically.
This ensures dependencies are set when the bean is created.
Preferred over setter injection for immutability and clarity.
If dependencies are missing, bean creation fails.
Use final fields to hold injected dependencies.
Full Transcript
Constructor injection in Spring Boot means that when Spring creates a bean, it calls the class constructor and passes in the required dependencies. This happens during application startup. Spring scans for components, finds the bean to create, identifies the constructor with parameters, and injects the dependencies by calling that constructor. The bean is then ready to use with all dependencies set. This method is preferred because it guarantees that dependencies are provided and the bean is immutable. If a required dependency is missing, Spring cannot create the bean and will throw an error. The example shows a Service class with a constructor that takes a Repo object. Spring injects the Repo instance when creating the Service bean.

Practice

(1/5)
1. What is the main advantage of using constructor injection in Spring Boot?
easy
A. It automatically creates objects without any code.
B. It requires less code than field injection.
C. It allows changing dependencies after the object is created.
D. It makes dependencies explicit and helps with testing.

Solution

  1. Step 1: Understand constructor injection purpose

    Constructor injection passes dependencies when creating the object, making them clear and fixed.
  2. Step 2: Benefits of explicit dependencies

    This clarity helps testing because dependencies can be easily replaced with mocks.
  3. Final Answer:

    It makes dependencies explicit and helps with testing. -> Option D
  4. Quick Check:

    Constructor injection = explicit dependencies [OK]
Hint: Constructor injection shows dependencies clearly [OK]
Common Mistakes:
  • Thinking constructor injection creates objects automatically
  • Confusing constructor injection with field injection
  • Believing dependencies can be changed after creation
2. Which of the following is the correct syntax for constructor injection in a Spring Boot component?
easy
A. public class Service { private final Repo repo; public Service(Repo repo) { this.repo = repo; } }
B. public class Service { @Autowired private Repo repo; }
C. public class Service { private Repo repo; public void setRepo(Repo repo) { this.repo = repo; } }
D. public class Service { private Repo repo = new Repo(); }

Solution

  1. Step 1: Identify constructor injection pattern

    Constructor injection requires a constructor that takes dependencies as parameters and assigns them.
  2. Step 2: Check each option

    public class Service { private final Repo repo; public Service(Repo repo) { this.repo = repo; } } shows a constructor with a parameter and assigns it to a final field, which is correct.
  3. Final Answer:

    public class Service { private final Repo repo; public Service(Repo repo) { this.repo = repo; } } -> Option A
  4. Quick Check:

    Constructor with parameters = constructor injection [OK]
Hint: Constructor injection needs constructor with parameters [OK]
Common Mistakes:
  • Using @Autowired on fields instead of constructor
  • Using setter methods instead of constructor
  • Creating new dependency instances inside the class
3. Given the code below, what will be the output when the printMessage method is called?
\@Component
public class Printer {
  private final MessageService service;
  public Printer(MessageService service) {
    this.service = service;
  }
  public void printMessage() {
    System.out.println(service.getMessage());
  }
}

\@Component
public class MessageService {
  public String getMessage() {
    return "Hello Spring!";
  }
}
medium
A. null
B. Hello Spring!
C. Compilation error
D. Runtime NullPointerException

Solution

  1. Step 1: Understand constructor injection wiring

    Spring injects MessageService into Printer via constructor, so service is not null.
  2. Step 2: Check method output

    Calling service.getMessage() returns "Hello Spring!", which is printed.
  3. Final Answer:

    Hello Spring! -> Option B
  4. Quick Check:

    Injected service returns message [OK]
Hint: Constructor injection ensures dependencies are not null [OK]
Common Mistakes:
  • Assuming service is null without injection
  • Confusing field injection with constructor injection
  • Expecting compilation error due to missing annotations
4. What is wrong with the following Spring Boot component using constructor injection?
\@Component
public class UserService {
  private final UserRepository repo;
  public UserService() {
    this.repo = null;
  }
}
medium
A. Constructor does not accept UserRepository, so dependency is not injected.
B. Field repo should not be final.
C. Missing @Autowired annotation on the constructor.
D. UserRepository should be instantiated inside the constructor.

Solution

  1. Step 1: Check constructor parameters for injection

    The constructor has no parameters, so Spring cannot inject UserRepository.
  2. Step 2: Understand consequence of no injection

    repo is assigned null manually, so dependency is missing and will cause errors later.
  3. Final Answer:

    Constructor does not accept UserRepository, so dependency is not injected. -> Option A
  4. Quick Check:

    Constructor must have dependency parameters [OK]
Hint: Constructor must accept dependencies as parameters [OK]
Common Mistakes:
  • Forgetting to add parameters to constructor
  • Thinking @Autowired is required on constructor in Spring Boot
  • Instantiating dependencies manually inside constructor
5. You have a Spring Boot service that depends on two other services: PaymentService and NotificationService. How should you write the constructor to follow best practices for constructor injection?
hard
A. public OrderService(PaymentService paymentService) { this.paymentService = paymentService; }
B. public OrderService() { this.paymentService = new PaymentService(); this.notificationService = new NotificationService(); }
C. public OrderService(PaymentService paymentService, NotificationService notificationService) { this.paymentService = paymentService; this.notificationService = notificationService; }
D. public OrderService(@Autowired PaymentService paymentService, NotificationService notificationService) { this.paymentService = paymentService; this.notificationService = notificationService; }

Solution

  1. Step 1: Identify correct constructor injection with multiple dependencies

    The constructor should accept all required dependencies as parameters and assign them.
  2. Step 2: Check options for best practice

    public OrderService(PaymentService paymentService, NotificationService notificationService) { this.paymentService = paymentService; this.notificationService = notificationService; } correctly accepts both services and assigns them, following best practice.
  3. Final Answer:

    public OrderService(PaymentService paymentService, NotificationService notificationService) { this.paymentService = paymentService; this.notificationService = notificationService; } -> Option C
  4. Quick Check:

    Constructor with all dependencies = best practice [OK]
Hint: Include all dependencies as constructor parameters [OK]
Common Mistakes:
  • Instantiating dependencies inside constructor
  • Missing one of the dependencies in constructor
  • Using @Autowired on constructor parameters unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard