Startup fails with NoUniqueBeanDefinitionException after someone adds a second implementation. Do you reach for @Primary, @Qualifier or a list of beans, and which fix ages badly?
NoUniqueBeanDefinitionException means one injection point matches two beans by type. Fix it where the decision belongs: a qualifier at the consumer when callers need different beans, a List or Map when all are used, a conditional bean when only one should exist. A primary bean is the quick fix that ages worst.
Answer
Short answer
Two beans now match one injection point by type. Pick the fix that matches why the second implementation exists: a @Qualifier at the consumer when different callers need different beans, an injected List or Map when the code uses all of them, and a conditional bean when only one should exist in a given environment. @Primary makes the error disappear fastest, and it is the fix most likely to surprise someone a year later.
Was this answer helpful?
Likely follow-ups
- A library you depend on also marks its implementation as primary. What happens at startup, and who should change?
- How would you test that every value of the payment-method enum has exactly one registered gateway?
- If one consumer needs the card gateway and twenty need the default, does that change your choice?
- What does injecting a Map of beans keyed by bean name couple your business logic to?
Related questions
- Why does @Transactional sometimes do nothing at all, even though the annotation is right there?mediumAlso on spring and dependency-injection4 min
- A method with REQUIRES_NEW was meant to save an audit row even when the main transaction fails. When does it work, and when does it deadlock?hardAlso on spring5 min
- After a Spring Boot upgrade the app refuses to start with a circular reference between two services. Do you turn the check off?mediumAlso on dependency-injection5 min
- A singleton service depends on a prototype-scoped bean, and every caller gets the same instance. Why, and how do you get a fresh one per use?mediumAlso on spring4 min