0Pricing
Spring Boot 4 Complete Guide · Lesson

Dependency Injection in Practice

Learn to use `@Autowired` and constructor injection for managing dependencies within your application.

Dependency Injection in Practice is a free Spring Boot 4 Complete Guide lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Spring Boot 4 Complete Guide learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

DI in Practice: Intro

Welcome to Dependency Injection in Practice! In Spring Boot, we don't manually create objects. Instead, Spring handles this for us, 'injecting' what an object needs.

This lesson focuses on the two primary ways to ask Spring to inject dependencies into your components: Field Injection and Constructor Injection.

What's a Dependency?

Think of dependencies as the 'ingredients' an object needs to do its job. For example, a CoffeeMaker might need a WaterHeater and a CoffeeBeanGrinder.

  • Dependency: An object that another object relies on.
  • Injection: Spring providing these required objects automatically.

This keeps your code cleaner and easier to test!

Field Injection with @Autowired

Field injection is the simplest way to tell Spring to inject a dependency. You place the @Autowired annotation directly above the field that needs the dependency.

Spring will then find a suitable bean (an object managed by Spring's IoC container) and assign it to that field.

Field Injection Example

Let's see field injection in action. Here, MyService needs an instance of MyComponent.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
class MyComponent {
  public String greet() {
    return "Hello from Component!";
  }
}

@Component
class MyService {
  @Autowired
  private MyComponent component;

  public void performAction() {
    System.out.println(component.greet());
  }
}

public class Main {
  public static void main(String[] args) {
    // In a real Spring app, Spring manages this.
    // For this example, we simulate it.
    MyComponent comp = new MyComponent();
    MyService service = new MyService();
    // Simulate injection (Spring does this automatically)
    service.component = comp;
    service.performAction();
  }
}

Field Injection: The Downsides

While easy, field injection has some drawbacks:

  • Testing: It's harder to unit test components without a Spring context because you can't easily pass mock dependencies.
  • Immutability: Fields can't be declared final, making objects mutable after creation.
  • Tight Coupling: It obscures the object's dependencies, making it less clear what it needs.

Most Spring developers prefer an alternative...

Constructor Injection: The Preferred Way

Constructor injection is generally considered the best practice for dependency injection. Here, dependencies are provided as arguments to the class's constructor.

This makes dependencies explicit and ensures that an object is fully initialized and valid upon creation.

Constructor Injection Example

Notice how MyService now requires MyComponent as a constructor argument. Spring automatically provides it!

import org.springframework.stereotype.Component;

@Component
class MyComponent {
  public String greet() {
    return "Hello from Component!";
  }
}

@Component
class MyService {
  private final MyComponent component;

  // Spring automatically injects MyComponent here
  public MyService(MyComponent component) {
    this.component = component;
  }

  public void performAction() {
    System.out.println(component.greet());
  }
}

public class Main {
  public static void main(String[] args) {
    // In a real Spring app, Spring manages this.
    // For this example, we simulate it.
    MyComponent comp = new MyComponent();
    MyService service = new MyService(comp); // Manual injection for demo
    service.performAction();
  }
}

@Autowired on Constructor?

When a class has only one constructor, Spring 4.3+ automatically treats it as a constructor for dependency injection. You don't need to add @Autowired explicitly.

If there are multiple constructors, you would use @Autowired on the specific constructor you want Spring to use for injection.

Which Injection Type to Choose?

Here's a quick guide:

  • Constructor Injection: Recommended for most cases. Promotes immutability, easier testing, and clear dependencies.
  • Field Injection: Avoid if possible. Can be used for optional dependencies or in very specific legacy scenarios.
  • Setter Injection: Useful for optional dependencies that might change during the object's lifecycle. Less common than constructor injection.

Test Your Knowledge!

Which statement best describes the primary benefit of Constructor Injection over Field Injection in Spring Boot?

Recap: DI in Practice

You've learned about practical dependency injection in Spring Boot!

  • Field Injection uses @Autowired directly on fields, but has drawbacks.
  • Constructor Injection is the preferred method, making dependencies explicit and promoting immutability.
  • Spring automatically handles constructor injection for single constructors.

Using the right injection type leads to more robust and testable applications. Next, we'll look at externalizing application properties!

Frequently asked questions

Is the “Dependency Injection in Practice” lesson free?

Yes — the full text of “Dependency Injection in Practice” is free to read here on the web, and the Spring Boot 4 Complete Guide course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Spring Boot 4 Complete Guide course, upgrade to CoddyKit PRO.

What will I learn in “Dependency Injection in Practice”?

Learn to use `@Autowired` and constructor injection for managing dependencies within your application. You practise Spring Boot 4 Complete Guide with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Spring Boot 4 Complete Guide?

No prior experience is required. Spring Boot 4 Complete Guide on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Dependency Injection in Practice” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Spring Boot 4 Complete Guide lesson?

Yes. Every Spring Boot 4 Complete Guide lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Understanding Spring IoC Container
  2. Dependency Injection in Practice
  3. Externalizing Application Properties
  4. Bean Scopes and Lifecycle Management
← Back to Spring Boot 4 Complete Guide