Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose what implementation get's injected in to an autowired constructor

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?

like image 499
Stewart Avatar asked Oct 11 '16 01:10

Stewart


1 Answers

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) {
        ...
    }

}
like image 192
luboskrnac Avatar answered Nov 09 '22 23:11

luboskrnac