Say I have an interface
interface IPerson {...}
I have two implementations of this interface
@Component
class Programmer implements IPerson {...}
@Component
class LionTamer implements IPerson {...}
Say I have a class that uses Autowire injection
@Component
class SomethingThatDoesStuff {
@Autowired
public SomethingThatDoesStuff (IPerson someone) {
...
}
}
How does Spring know what implementation to inject? Is there a way to tell spring what implementation to inject? Can this be done via the annotation or do I have to define some sort of factory? If so how?
As @passion mentioned, you should use bean naming (standard Spring IoC feature):
@Component("programmer")
class Programmer implements IPerson {...}
@Component("lionTamer")
class LionTamer implements IPerson {...}
@Component
class SomethingThatDoesStuff {
@Autowired
public SomethingThatDoesStuff (@Qualifier("programmer") IPerson someone) {
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With