简体   繁体   English

在两个 bean 中注入 spring bean-实现相同的接口

[英]Injecting spring bean among two beans- implementing same interface

I have two spring bean classes which are implemeting the same interface.我有两个实现相同接口的 spring bean 类。

 public interface Abc()
  {
    String getNumber();
  }

The two classes are这两个类是

 @Service
 public class SomeClass implements abc
  {

  @Override
  public class getNumber()
  {


  }

 }


 @Service
 public class SomeClass1 implements abc
 {

  @Override
  public class getNumber()
  {

  }
  }

In my Service class.在我的服务课上。

 @Service
 public class Demo
  {

  @Autowired
  private Abc abc;

  }

  }

I got an error "required a single bean, but 2 were found"我收到错误消息“需要一个 bean,但找到了 2 个”

For that error i can have the chance to put @Primary in the top of one of the bean.对于那个错误,我可以有机会将@Primary 放在其中一个 bean 的顶部。

But i have only way to say "one bean configuration" based on the value which i will get in runtime(From the database).但我只能根据我将在运行时(从数据库)获得的值来说“一个 bean 配置”。

Can you please suggest me a way.你能给我一个方法吗?

You can autowire a list of interfaces and then choose the right one.您可以自动装配接口列表,然后选择正确的接口。 You can write:你可以写:

@Autowired
List<Abc> abcs;

this will result in a list of implementations of the interface.这将导致接口的实现列表。 In your method body you can then choose the right one.然后在您的方法体中,您可以选择正确的方法。

Couple of ways you can autowire the correct implementation.您可以通过几种方式自动装配正确的实现。

Change your autowired field name to the same name of the implementation class (in camelcase)将您的自动装配字段名称更改为与实现类相同的名称(驼峰式)

@Autowired
private Abc someClass;

This will attempt to find an implementation of interface 'Abc' with the classname 'SomeClass'.这将尝试找到类名为“SomeClass”的接口“Abc”的实现。

Another way is to add a bean name to your service annotation另一种方法是将 bean 名称添加到您的服务注释中

@Service("someClass")
public class SomeClass implements abc

This can then be autowired like the following然后可以像下面这样自动装配

@Autowired
@Qualifier("someClass")
private Abc SomeClass;

I think the problem he is asking about how to configure two implentation and also using the right bean dynamically(based on data in DB).我认为他问的问题是如何配置两个实现以及动态使用正确的 bean(基于数据库中的数据)。 It seems this is the an example for factory pattern看来这是工厂模式的一个例子

Psuedo Code伪代码

Class SomeFactory{
 @Autowired
 private Abc someClass;
  @Autowired
  private Abc someClass1;// keeping bean Name same as class name would solve bean finding issue

public Abc getBeanFor(String type) {
if("someClass".equals(type)
    return someClass;
  return someClass1;
} 
}

Class TestClass{
 @Autowired
   private SomeFactory factory ;
  private void someProcess() {
   // Read type from DB for data

   factory.getBeanFor(typeReadFromData)
                .process();
 } 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM