Junior — Middle
Which dependency injection method for Beans in Spring is considered most recommended?
sobes.tech AI
Answer from AI
The most recommended method of dependency injection for Beans in Spring is constructor injection. This approach has several advantages:
- Ensures immutability of dependencies after object creation.
- Allows explicit declaration of required dependencies.
- Improves testability, as dependencies can be easily replaced.
Example of constructor injection:
@Component
public class MyService {
private final Dependency dependency;
@Autowired
public MyService(Dependency dependency) {
this.dependency = dependency;
}
// class methods
}
Although Spring also supports injection via setters and fields, constructor injection is considered more reliable and preferred in modern applications.