具有多个接口实现的Spring Autowire Bean,在方法中定义实现 [英] Spring Autowire Bean with multiple Interface Implementations, define Implementation in method
问题描述
我是春季和春季靴子的新手,所以希望这不是一个愚蠢的问题.
I am new to spring and spring boot, so hopefully it is not a silly question.
我有一个带有几种实现的接口.用@Component("NameOfImpl")
注释实现.
I have an interface with several implementations. Implementations are annotated with @Component("NameOfImpl")
.
我的目标是使用选定的实现对bean进行自动装配.通常情况下,我可以使用@Autowired @Qualifier("NameOfImpl")
来做到这一点,但是我的问题是我想在一种方法中选择一种实现:
My goal is to autowire a bean with selected implementation. In a normal case I can do it with @Autowired @Qualifier("NameOfImpl")
, but my Problem is I want to select an Implementation in a method like:
public void doSomethingMethod(){
for(String line: configFile){
String[] values = line.split(";");
if (values[0].equals("A")) {
//here I want to select an bean implementation
}
else if (values[0].equals("B")) {
//here I want to select another bean implementation
}
}
bean.doSomething();
}
我该如何实现?你有什么建议? 谢谢!
How can I achieve that? What do you suggest? Thank you!
推荐答案
您可以要求Spring注入Map
的bean.地图中的键将是bean的名称.
You can ask Spring to inject a Map
of beans. The keys in the map will be the beans' names.
如果您有一个名为Example
public interface Example {
}
以及两种实现方式:
@Component("foo")
public class FooExample implements Example {
}
@Component("bar")
public class BarExample implements Example {
}
您可以插入一张Example
豆的地图:
You can have a map of Example
beans injected:
@Component
public class ExampleConsumer {
private final Map<String, Example> examples;
@Autowired
public ExampleConsumer(Map<String, Example> examples) {
this.examples = examples;
}
}
在这种情况下,地图将包含两个条目:
In this case the map will contain two entries:
-
"foo"
->FooExample
实例 -
"bar"
->BarExample
实例
"foo"
->FooExample
instance"bar"
->BarExample
instance
这篇关于具有多个接口实现的Spring Autowire Bean,在方法中定义实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!