I'm new to Spring and Dependancy Injection, so I'll do my best, but this question may not be perfectly formed.
In short, imagine a 'sandwich' program that has a 'cheese' component. swiss cheese and provalone cheese both fit the interface, so they can both be used in our sandwich. Our code might look something like this.
class Sandwich{
@Autowired
Meat m;
@Autowired
Cheese c;
}
@Component
class Ham implements Meat{
}
@Component
class Swiss implements Cheese{
}
@Component
class Provolone implements Cheese{
}
It is obvious that spring framework will use ham as the meat; it’s the only meat component. But how does spring framework choose between Swiss and provolone? Is there some further setup required by the programmer? If so, how is this not tight coupling?
Thanks for the info! This enterprise level coding is new (and slightly intimidating) to me, so any input is appreciated.
This articles covers it well https://www.baeldung.com/spring-autowire#disambiguation
But in short, Spring follows the following steps:
ApplicationContext. If there is only one qualifying bean, it will inject the bean@Qualifierannotation on the field. If there is an annotation, it will use the logic within to determine which bean to injectI would suggest in your example either instantiate only one bean of type cheese. You can do this by annotating the classes with a
@Profileannotation and use runtime profile values to select which one to instantiate.Alternatively, you can declare
List<Cheese> cand Spring will inject both cheeses into the variable as aList. Then you can choose which cheese to invoke during runtime from theListbased on your business logic.