Senior
How does Spring resolve beans if there are multiple implementations of the same interface?
sobes.tech AI
Answer from AI
If there are multiple implementations of the same interface in the Spring container, ambiguity arises during autowiring by type. Spring resolves beans as follows:
- If the
@Qualifierannotation is used, Spring selects the bean with the specified name or qualifier. - If one of the beans is marked as
@Primary, it will be chosen by default. - If neither
@Qualifiernor@Primaryis specified, and there are multiple candidates, anNoUniqueBeanDefinitionExceptionis thrown during autowiring.
Example:
public interface Service {
void execute();
}
@Component
@Primary
public class ServiceImpl1 implements Service {
public void execute() { /* implementation 1 */ }
}
@Component
public class ServiceImpl2 implements Service {
public void execute() { /* implementation 2 */ }
}
@Component
public class Client {
private final Service service;
@Autowired
public Client(Service service) {
this.service = service; // ServiceImpl1 will be injected because it is @Primary
}
}
To explicitly specify which implementation to use, @Qualifier is applied:
@Autowired
public Client(@Qualifier("serviceImpl2") Service service) {
this.service = service; // ServiceImpl2 will be injected
}