如何选择将实现注入到自动装配的构造函数中

时间:2016-10-11 01:31:31

标签: java spring spring-boot inversion-of-control autowired

说我有一个界面

interface IPerson {...}

我有两个这个接口的实现

@Component
class Programmer implements IPerson {...}

@Component
class LionTamer implements IPerson {...}

假设我有一个使用Autowire注入的课程

@Component
class SomethingThatDoesStuff { 

    @Autowired
    public SomethingThatDoesStuff (IPerson someone) {
        ...
    }

}

Spring如何知道要注入的实现?有没有办法告诉spring注入什么实现?这可以通过注释完成,还是我必须定义某种工厂?如果是这样的话?

1 个答案:

答案 0 :(得分:4)

正如@passion所提到的,你应该使用bean命名(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) {
        ...
    }

}