Middle
Why is there no need to specify the @Autowired annotation in modern Spring?
sobes.tech AI
Answer from AI
Starting from Spring 4.3, if a class has only one constructor, Spring automatically injects dependencies through that constructor, even without @Autowired.
When there are multiple constructors, Spring still requires the @Autowired annotation to explicitly specify which constructor to use for dependency injection.
Example with a single constructor:
// Example of a class with one constructor
public class MyService {
private final SomeDependency dependency;
public MyService(SomeDependency dependency) { // Spring will automatically inject SomeDependency
this.dependency = dependency;
}
// ... other methods
}
Example with multiple constructors and @Autowired:
// Example of a class with multiple constructors
public class MyOtherService {
private final AnotherDependency anotherDependency;
private final OptionalDependency optionalDependency;
// Constructor without dependencies
public MyOtherService() {
this.anotherDependency = null;
this.optionalDependency = null;
}
@Autowired // Spring will use this constructor for injection
public MyOtherService(AnotherDependency anotherDependency, OptionalDependency optionalDependency) {
this.anotherDependency = anotherDependency;
this.optionalDependency = optionalDependency;
}
@Autowired(required = false) // Additional constructor using OptionalDependency
public MyOtherService(OptionalDependency optionalDependency) {
this.anotherDependency = null;
this.optionalDependency = optionalDependency;
}
// ... other methods
}
This feature reduces boilerplate code and makes classes more readable, especially with Constructor Injection. It is the recommended way of dependency injection in modern Spring applications, as it promotes creating immutable objects and simplifies testing.