Middle+
What is executed first: constructor, setter, or field injection?
sobes.tech AI
Answer from AI
Order of execution when creating a bean in the Spring context (without explicit configurations affecting this order):
- Constructor: Called first to create the object instance.
- Field and setter injection: After creating the object, Spring injects dependencies via fields (@Autowired) and setters (@Autowired on setter). The order between field and setter injection is not explicitly guaranteed and may depend on the specific Spring version or configuration, but both operations occur after the constructor.
If multiple dependencies are injected into the same bean, the order of their injection (whether fields or setters) is not deterministic.
Example using @Autowired annotations:
public class MyBean {
@Autowired
private SomeDependency fieldDependency;
private OtherDependency setterDependency;
public MyBean() {
// This code executes first
System.out.println("Constructor called");
}
@Autowired
public void setSetterDependency(OtherDependency setterDependency) {
// This code executes after the constructor and possibly after field injection
this.setterDependency = setterDependency;
System.out.println("Setter called");
}
// When using @Autowired for a field, it is injected after the constructor,
// but whether before or after the setter is not explicitly guaranteed.
}