Middle+
What bean injection methods do you know in Spring?
sobes.tech AI
Answer from AI
In the Spring Framework, there are several main ways to inject beans:
- Constructor Injection — dependencies are passed through the class constructor parameters. This is the preferred method as it allows creating immutable objects and simplifies testing.
@Component
public class Service {
private final Repository repo;
@Autowired
public Service(Repository repo) {
this.repo = repo;
}
}
- Setter Injection — dependencies are set through setter methods. It allows changing dependencies after object creation.
@Component
public class Service {
private Repository repo;
@Autowired
public void setRepository(Repository repo) {
this.repo = repo;
}
}
- Field Injection — dependencies are injected directly into class fields using the
@Autowiredannotation. It is less preferred due to testing complexity and encapsulation issues.
@Component
public class Service {
@Autowired
private Repository repo;
}
Each method has its pros and cons, but constructor injection is considered the cleanest and most recommended practice.