(...) by using Constructor Injection, you assert the requirement for the dependency in a container-agnostic manner
This mean that you can enforce requirements for all injected fields without using any container specific solution.
With setter injection special spring annotation @Required
is required.
@Required
Marks a method (typically a JavaBean setter method) as being 'required': that is, the setter method must be configured to be dependency-injected with a value.
Usage
import org.springframework.beans.factory.annotation.Required;
import javax.inject.Inject;
import javax.inject.Named;
@Named
public class Foo {
private Bar bar;
@Inject
@Required
public void setBar(Bar bar) {
this.bar = bar;
}
}
All required fields are defined in constructor, pure Java solution.
Usage
import javax.inject.Inject;
import javax.inject.Named;
@Named
public class Foo {
private Bar bar;
@Inject
public Foo(Bar bar) {
this.bar = bar;
}
}
This is especially useful in Unit Testing. Such kind of tests should be very simple and doesn't understand annotation like @Required
, they generally not need a Spring for running simple unit test. When constructor is used, setup of this class for testing is much easier, there is no need to analyze how class under test is implemented.