If I have an interface with multiple implementing classes, how does dependency injection in Spring Boot know which bean to inject? I want to avoid runtime conflicts and ensure my software development team follows a standardized configuration strategy.
3 answers
When you have multiple implementations for an interface, dependency injection in Spring Boot will fail with a NoUniqueBeanDefinitionException unless you guide it. You can resolve this by using the @Qualifier annotation alongside your injection point to specify the exact bean name you want. Alternatively, you can mark one of your implementation classes with the @Primary annotation, which tells the framework to default to that specific bean whenever no qualifier is explicitly provided.
Is it considered a bad practice to rely heavily on @Primary, or should we make it a rule to always use @Qualifier to be as explicit as possible in our code?
You can also inject all implementations into a List or a Map if you need to dynamically select an strategy pattern implementation at runtime.
Rebecca is right on target. Injecting a Map where the key matches the bean name is an incredibly elegant way to implement the strategy pattern in modern software development.
It is not bad practice, Douglas. Use @Primary for the default behavior that applies 80% of the time, like a standard database service. Use @Qualifier for specific edge cases, like a secondary backup service, to keep the configuration clean and highly readable.