Junior — Middle
How to select a specific Bean when there are multiple with the same name in the Spring context?
sobes.tech AI
Answer from AI
In Spring, if there are multiple Beans with the same name in the context (which is generally not recommended, as names should be unique), you can use the @Qualifier annotation along with @Autowired to select a specific Bean.
Example:
@Component("myBean")
public class MyBeanImpl1 implements MyBeanInterface { ... }
@Component("myBean")
public class MyBeanImpl2 implements MyBeanInterface { ... }
// At the injection point
@Autowired
@Qualifier("myBeanImpl1")
private MyBeanInterface myBean;
If names match, it is better to assign unique names or use the @Primary annotation to specify the main Bean. You can also inject a collection of all Beans and choose the required one programmatically.