java-如何选择将什么实现注入自动构造函数
作者:互联网
说我有一个界面
interface IPerson {...}
我有此接口的两种实现
@Component
class Programmer implements IPerson {...}
@Component
class LionTamer implements IPerson {...}
说我有一个使用Autowire注入的课程
@Component
class SomethingThatDoesStuff {
@Autowired
public SomethingThatDoesStuff (IPerson someone) {
...
}
}
Spring如何知道要注入的实现?有没有办法告诉spring要注入什么实现?可以通过注释完成此操作,还是必须定义某种工厂?如果可以,怎么办?
解决方法:
如@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) {
...
}
}
标签:spring-boot,autowired,spring,java,inversion-of-control 来源: https://codeday.me/bug/20191026/1937875.html