具有多个接口实现的Spring Autowire Bean,在方法中定义实现 [英] Spring Autowire Bean with multiple Interface Implementations, define Implementation in method

查看:338
本文介绍了具有多个接口实现的Spring Autowire Bean,在方法中定义实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是春季和春季靴子的新手,所以希望这不是一个愚蠢的问题.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆