Understanding Dependency Injection Types in Spring: Constructor, Setter, and Field Injection
The article explains Spring’s three dependency‑injection styles—constructor, setter, and field—showing how constructor injection (often with @Autowired or implicit) enables immutable, required dependencies, setter injection handles optional ones, and field injection, though concise, is discouraged due to immutability, testability, and coupling drawbacks.
Spring officially discourages the use of @Autowired field/property injection, and many companies forbid it in new projects.
The article explains the three types of dependency injection supported by Spring 5.1.3: constructor‑based, setter‑based, and field‑based injection, and discusses when each should be used.
Constructor‑based injection marks the class constructor with @Autowired (or omits it) and allows injected fields to be declared final, ensuring immutability.
@Component
public class ConstructorBasedInjection {
private final InjectedBean injectedBean;
@Autowired
public ConstructorBasedInjection(InjectedBean injectedBean) {
this.injectedBean = injectedBean;
}
}Setter‑based injection annotates a setter method with @Autowired; the container calls the setter after creating the bean.
@Component
public class SetterBasedInjection {
private InjectedBean injectedBean;
@Autowired
public void setInjectedBean(InjectedBean injectedBean) {
this.injectedBean = injectedBean;
}
}Field‑based injection directly annotates a member variable with @Autowired. It results in concise code but has several drawbacks.
Drawbacks of field injection include:
Cannot declare immutable (final) dependencies.
Can hide the growing number of dependencies, violating the Single Responsibility Principle.
Creates tight coupling to the Spring container, making the class hard to use outside the container or in unit tests.
Hides dependencies from the public API.
The article recommends preferring constructor injection for required dependencies and setter injection for optional ones, while avoiding field injection whenever possible.
References: “Field injection is not recommended – Spring IOC” by Marc Nuri and Spring official documentation.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.