Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 10

Constructor Injection vs. Module Imports in Node.js

This lesson is built with resources from youtube.com, blog.scottlogic.com and 1 more site.

Hello! In our previous lesson, we took a big step by defining our first Spring components, BlogService and BlogRepository, and used the debugger to watch the IoC container bring them to life. We saw that while the container created these objects, they exist in isolation. The BlogService has no way to access the BlogRepository.

Today, we'll bridge that gap. We're going to implement Dependency Injection (DI), the core mechanism Spring uses to wire components together. You'll learn how to make the BlogService receive an instance of BlogRepository automatically, using the modern, recommended approach: constructor injection. We'll draw direct comparisons to how you've managed dependencies in your Node.js projects to solidify the concept.

1. What is Dependency Injection?

In the last lesson, we learned about Inversion of Control (IoC), where we hand over the control of object creation to the Spring container. Dependency Injection (DI) is the how. It's the concrete design pattern used to implement IoC.

Instead of a component creating its own dependencies (e.g., this.repository = new BlogRepository();), the dependencies are "injected" or "passed into" the component by the IoC container.

Spring IoC Container as an Object Factory
This diagram illustrates the core idea of IoC and DI. Your application (or a component within it) declares that it needs an object. The Spring Container acts as a factory, figures out which specific implementation to create based on its configuration, and provides it to your application.

This creates a loosely coupled system. Your BlogService doesn't need to know how to construct a BlogRepository; it only needs to know that it requires an implementation of one. This makes your code more modular, easier to test, and more flexible.

To better understand this concept of loose coupling, let's watch a short, insightful explanation.

Dependency Injection & Inversion of Control

The video 'Dependency Injection & Inversion of Control' by Ryan Schachte uses a great analogy to explain why hard-coding dependencies is a bad idea.

Watch the segment from 0:16 to 2:10. Pay close attention to the 'lamp and outlet' analogy. This perfectly describes the problem of tightly-coupled components and how IoC solves it by promoting a 'pluggable' architecture.

MERN Stack Comparison

In your experience with Node.js and Express, you've already practiced a form of dependency injection, likely a manual one.

// Manual Dependency Injection in Node.js
import { UserService } from './services/user.service';
import { UserRepository } from './repositories/user.repository';

// You create the dependency
const userRepository = new UserRepository(); 
// You inject it into the service via the constructor
const userService = new UserService(userRepository); 

Some advanced Node.js frameworks like NestJS (which uses inversify or typedi under the hood) automate this, making it look very similar to Spring.

// Automated DI in a framework like NestJS
@Injectable()
export class UserService {
  constructor(private readonly userRepository: UserRepository) {} // The framework injects this
}

Spring's approach is like the second example: powerful, declarative, and automated.


2. Implementing Constructor Injection

Spring supports three main types of dependency injection:

  1. Constructor Injection: Dependencies are passed as arguments to the constructor.
  2. Setter Injection: Dependencies are passed via public setter methods.
  3. Field Injection: Dependencies are injected directly into fields, usually using @Autowired.

Constructor injection is the recommended approach in modern Spring applications. Let's see why as we implement it.

Hands-On: Wiring the Service and Repository

We will now modify our BlogService to declare its dependency on BlogRepository.

  1. Open BlogService.java in your service package.
  2. Add a private final field for BlogRepository. The final keyword is a best practice here; it signals that this dependency is required and will not change after the object is constructed.
  3. Generate a constructor that accepts BlogRepository as an argument. Your IDE can do this for you (in IntelliJ, Alt+Insert -> Constructor).

Your BlogService.java should now look like this:

package com.blogplatform.blogplatform.service;

import com.blogplatform.blogplatform.repository.BlogRepository;
import org.springframework.stereotype.Service;

@Service
public class BlogService {

    private final BlogRepository blogRepository;

    // Spring will call this constructor and provide the BlogRepository bean
    public BlogService(BlogRepository blogRepository) {
        System.out.println("BlogService constructor called. Injecting BlogRepository.");
        this.blogRepository = blogRepository;
    }

    public String getRepositoryData() {
        // We can now use the injected repository
        return "Data from repository: " + blogRepository.findData();
    }
}
  1. Next, let's add a simple method to BlogRepository.java so we can prove the connection works.
package com.blogplatform.blogplatform.repository;

import org.springframework.stereotype.Repository;

@Repository
public class BlogRepository {
    public BlogRepository() {
        System.out.println("BlogRepository bean has been created!");
    }

    public String findData() {
        return "Raw data found!";
    }
}

You might be asking: "Where is the @Autowired annotation?" Since Spring Framework 4.3, if a class has only one constructor, the @Autowired annotation is optional. Spring is smart enough to know that it must use this constructor for instantiation and dependency injection. This keeps the code clean and is the idiomatic way to write components today.


3. Runtime Observation: Verifying the Injection

How can we be sure the injection worked? We'll create a temporary controller to trigger our service and observe the result.

  1. Create a new package named controller.
  2. Inside controller, create a new class TestController.java.
package com.blogplatform.blogplatform.controller;

import com.blogplatform.blogplatform.service.BlogService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController // Marks this as a controller that handles HTTP requests
public class TestController {

    private final BlogService blogService;

    // The BlogService bean is injected here
    public TestController(BlogService blogService) {
        this.blogService = blogService;
    }

    @GetMapping("/test-di")
    public String testDependencyInjection() {
        return blogService.getRepositoryData();
    }
}

Notice we're using constructor injection in our TestController as well! This is the standard pattern.

Task 1: Run and Test

  1. Run the application. Check the console logs. You should see the messages from both constructors, indicating the beans were created.
  2. Open your browser or Postman and navigate to http://localhost:8080/test-di.
  3. You should see the response: Data from repository: Raw data found!

This confirms the entire chain is wired correctly: The HTTP request was handled by TestController, which called BlogService, which in turn called BlogRepository. The IoC container managed all the wiring for you.

Task 2: Debug the Constructor

Let's see the injection happen live.

  1. Set a breakpoint on the this.blogRepository = blogRepository; line inside the BlogService constructor.
  2. Run the application in Debug Mode.
  3. The execution will pause at your breakpoint. Hover over the blogRepository parameter in the debugger. You'll see it's a fully instantiated object, not null. The container created the BlogRepository first and is now passing it into the BlogService.

For a deeper dive into what's happening under the hood, this article demystifies the process by using the debugger, just as we are.

Spring Autowiring - It's a kind of magic - Part 1

The article 'Spring Autowiring - It's a kind of magic - Part 1' by Paul Graham is perfect for our debugging-first approach. It explores how Spring handles injection both with and without @Autowired.

Read the sections 'Autowiring with a single constructor' and the subsequent section analyzing the stack trace. The key takeaway is how Spring uses Java Reflection (specifically determineCandidateConstructors and Constructor.newInstance()) to automatically discover and use our single constructor for dependency injection.


4. Why Constructor Injection Is King

You will see field injection (@Autowired on a field) in older codebases, but it's now considered a bad practice. Let's understand why constructor injection is superior.

Spring Constructor Injection: Why is it the recommended approach to Dependency Injection?

The video 'Spring Constructor Injection' by Dan Vega gives a fantastic, practical breakdown of the different injection types and a compelling argument for using constructor injection.

Watch the segment from 16:57 to 24:35. The presenter compares constructor, setter, and field injection. Focus on the three key benefits of constructor injection he highlights: immutability (final fields), guaranteed dependency resolution (no NullPointerException), and improved testability.

To summarize the key advantages:

  • Immutability: Dependencies can be final, ensuring they are set at construction and never changed. This helps create robust, thread-safe beans.
  • Explicit Dependencies: A class's constructor signature clearly defines all its required dependencies. It's impossible to instantiate the object without them.
  • No Nulls: You are guaranteed that your dependencies are not null within the class's methods (assuming the IoC container is managing its lifecycle).
  • Superior Testability: It's trivial to write a unit test. You can simply instantiate your class with mocked dependencies: new BlogService(mockedRepository). Field injection requires more complex test setups involving reflection or Spring's test framework.

5. Debugging Exercise: The Infamous NoSuchBeanDefinitionException

Let's intentionally break our application to see one of the most common Spring startup errors.

  1. The Bug: Open BlogRepository.java and comment out or delete the @Repository annotation.

  2. The Symptom: Rerun your BlogPlatformApplication. The application will fail to start, and you'll see a very long, intimidating stack trace in the console.

  3. The Analysis: Don't panic. Scroll through the logs until you find the root cause. Spring is usually very descriptive. You're looking for something like this:

    ***************************
    APPLICATION FAILED TO START
    ***************************
    
    Description:
    
    Parameter 0 of constructor in com.blogplatform.blogplatform.service.BlogService required a bean of type 'com.blogplatform.blogplatform.repository.BlogRepository' that could not be found.
    
    Action:
    
    Consider defining a bean of type 'com.blogplatform.blogplatform.repository.BlogRepository' in your configuration.
    

    This error message is gold. It tells you exactly what went wrong:

    • Where: "Parameter 0 of constructor in BlogService"
    • What: "required a bean of type BlogRepository"
    • Why: "that could not be found."

    Spring tried to create the BlogService bean, saw it needed a BlogRepository for its constructor, looked in the IoC container, and found nothing registered. By removing @Repository, we stopped the container from ever creating the bean in the first place.

  4. The Fix: Uncomment the @Repository annotation in BlogRepository.java and rerun. The application will start successfully.


Conclusion

You have now mastered a cornerstone of the Spring framework. You've learned not just how to use Dependency Injection, but why the recommended pattern—constructor injection—leads to cleaner, more robust, and more testable code. You also diagnosed your first major DI-related runtime error by reading the stack trace.

Key Takeaways:

  • Dependency Injection (DI) is the pattern where components receive their dependencies from an external source (the IoC container) rather than creating them.
  • Constructor Injection is the preferred DI method in Spring. It makes dependencies explicit and required.
  • If a class has only one constructor, Spring uses it for DI automatically without needing an @Autowired annotation.
  • The NoSuchBeanDefinitionException is a common startup error that occurs when the IoC container cannot find a bean required for injection.

Preview of the next lesson:
We've hardcoded some System.out.println statements for debugging. This isn't scalable or professional. In the next lesson, we will introduce application.properties (and its more powerful cousin, application.yml) to configure our application externally. We'll start by changing the server port and then dive into configuring Spring's logging framework to get detailed, structured output, giving us even more insight into the framework's behavior.