Junior — Middle
What methods exist in Spring for handling the situation when multiple Beans implement the same interface?
sobes.tech AI
Answer from AI
In Spring, when multiple Beans implement the same interface, there are several ways to resolve ambiguity during dependency injection:
- @Qualifier — allows explicitly specifying which Bean to inject, using the name or a custom qualifier.
@Autowired
@Qualifier("beanName")
private MyInterface myBean;
- @Primary — marks one of the Beans as the primary, which will be used by default if no qualifier is specified.
@Primary
@Component
public class PrimaryBean implements MyInterface {}
- Injecting a collection of Beans — you can inject all implementations of the interface as a list or map:
@Autowired
private List<MyInterface> beans;
- Using Bean name — injection by name via
@Resource(name = "beanName").
These methods help manage situations with multiple implementations of a single interface and select the appropriate one depending on the context.