用户案例:
我们得到了一堆 Autowiring 的 bean,每个都由 @Service 注释,比如 B1、B2 和 B3,具有相同的接口(interface) BInterface。
在类 A 的方法中,我需要根据键字符串通过接口(interface)使用其中一个,比如“b1”、“b2”和“b3”。
我可以为此使用 hashmap Key -> BInterface 但我感兴趣的是它是否是任何 Spring 优雅(惯用语)方式来动态注入(inject)我需要的 bean。我也知道 getBean 被认为是一种反模式。
我不知道这是否重要,但上下文定义为注释驱动。
最佳答案
Spring 的方法是让你的三个 bean 实现三个不同的接口(interface)(或子接口(interface)),然后用 @Autowired
引用这三个接口(interface)。注解。毕竟,如果这三个 bean 具有不同的功能,那么这样做是有意义的。
你也可以有一个包含这三个的 bean,并且它是 @Autowired
所以你不需要到处都需要这三个引用。
我什至不确定 @Service
如果有更多相同接口(interface)的实例,将会正确连接。它适用于具体类,但我认为它不适用于接口(interface)的许多实现。
这是我建议的示例:
interface BInterface{ /*...*/ }
@Service
class B1 extends BInterface{/*...*/}
@Service
class B2 extends BInterface{/*...*/}
@Service
class B3 extends BInterface{/*...*/}
@Service
class BProvider {
@Autowired
private B1 b1;
@Autowired
private B2 b2;
@Autowired
private B2 b2;
public BInterface get(String k) {
switch(k){
case "b1": return b1;
case "b2": return b2;
case "b3": return b3;
default: return b1;
}
}
}
BClient {
@Autowired
private BProvider provider;
public void doSomething(){
BInterface b = provider.get(/* one of the three */);
// use b ...
}
}
作为替代方案,您可以制作 BProvider
可配置并使用 Map<String,BInterface>
配置它使用 XML 配置。
那就是:
@Service
class BProvider {
@Autowired
private Map<String,BInterface> bs;
public BInterface get(String k) {
return bs.get(k);
}
}
而且你必须在配置文件中定义你的 map 。为此,您可以在 XML 文件中手动创建 bean,或者我相信您可以使用 BeanPostProcessor
将它们添加到集合中。
关于java - 在注释驱动的上下文中 Autowiring bean 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21340013/