Junior — Middle
How does Spring handle the situation when multiple Beans implement the same interface?
sobes.tech AI
Answer from AI
When multiple beans in the Spring context implement the same interface, and an autowiring attempt is made (for example, using @Autowired), ambiguity arises because Spring does not know which bean to choose.
How does Spring handle this situation:
- If no specific bean is indicated, a
NoUniqueBeanDefinitionExceptionwill be thrown. - To resolve this, you can:
- Use the
@Qualifierannotation with the name of the desired bean. - Mark one bean as
@Primary, so it will be chosen by default. - Inject a collection of all beans of this type (
List<Interface>,Map<String, Interface>) to get all implementations.
- Use the
Example with @Qualifier:
@Autowired
@Qualifier("myServiceImpl")
private MyService myService;
Example with @Primary:
@Service
@Primary
public class PrimaryServiceImpl implements MyService {
// implementation
}
Thus, Spring requires explicit indication of which bean to use if there are multiple for the same type.