0
0
Spring Bootframework~5 mins

Field injection and why to avoid it in Spring Boot

Choose your learning style9 modes available
Introduction

Field injection automatically fills class fields with needed parts. But it hides how things connect, making code harder to understand and test.

When you want to quickly add a dependency without writing extra code.
In small projects or prototypes where speed is more important than structure.
When you are learning Spring and want to see how injection works simply.
When you have simple classes with few dependencies and no testing needs.
When you want to avoid writing constructors or setter methods.
Syntax
Spring Boot
@Autowired
private SomeService someService;
Field injection uses the @Autowired annotation directly on a class field.
Spring will fill this field automatically when creating the object.
Examples
This example shows a private field userService filled by Spring automatically.
Spring Boot
public class MyClass {
    @Autowired
    private UserService userService;
}
Here, emailSender is injected and used inside a method.
Spring Boot
public class MyClass {
    @Autowired
    private EmailSender emailSender;

    public void send() {
        emailSender.sendEmail();
    }
}
Sample Program

This Spring Boot example shows field injection where NotificationService has a private field messageSender filled by Spring. When notifyUser() runs, it uses messageSender to print a message.

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

@Component
public class NotificationService {

    @Autowired
    private MessageSender messageSender;

    public void notifyUser() {
        messageSender.send("Hello user!");
    }
}

@Component
class MessageSender {
    public void send(String message) {
        System.out.println("Sending message: " + message);
    }
}
OutputSuccess
Important Notes

Field injection hides dependencies, making it hard to see what a class needs.

It makes unit testing difficult because you cannot easily provide mock dependencies.

Constructor injection is preferred because it clearly shows dependencies and supports testing better.

Summary

Field injection uses @Autowired on fields to inject dependencies automatically.

It is easy but hides how classes connect and makes testing harder.

Constructor injection is a better practice for clear, testable code.