简体   繁体   English

将 String 的映射填充到公共接口的 Spring bean

[英]Populating map of String to Spring beans of a common interface

In my Spring boot application, I have an interface as follows:在我的 Spring Boot 应用程序中,我有一个如下界面:

 public interface I {
    
 }

I have two concrete classes implementing the interface I as follows:我有两个具体的类实现接口I如下:

 @Component
 class A implements I {
     private final B dependency1;
     
     public A(B b) {
         this.dependency1 = b;
     }
 }

And second class as follows:第二类如下:

@Compeonent
class C implements I {
     private final D dependency2;
     
     public C(D d) {
         this.dependency2 = d;
     }
 }

Now in a factory class, I am building a map to get the object of specific class depending on some criteria as follows:现在在工厂类中,我正在构建一个映射以根据某些条件获取特定类的对象,如下所示:

  class Factory {

 
  Map<String, I> criteriaToClassMap = new HashMap<>();

  criteriaToClassMap.put("criteria1", new A()); <--I CANNOT DECIDE WHAT TO PUT HERE
  criteriaToClassMap.put("criteria2", new C()); <--I CANNOT DECIDE WHAT TO PUT HERE

   //Here I would like to get fully constructed object
   public I getObject(String criteria) {
       return criteriaToClassMap.get(criteria);
   }
}

In the above two lines, I would like to put a fully constructed object in the value.在上面两行中,我想在 value 中放置一个完全构造的对象。 But I cannot understand how will I get the fully constructed object from Spring here.但是我无法理解我将如何从 Spring 获得完全构造的对象。

Could anyone please help here?有人可以在这里帮忙吗?

Why not use the created components?为什么不使用创建的组件?

@Component
class Factory {

   Map<String, I> criteriaToClassMap = new HashMap<>();

   public Factory (A a, C c) {
       criteriaToClassMap.put("criteria1", a); //<-- use autowired A component
       criteriaToClassMap.put("criteria2", c); //<-- use autowired C component
   }

   public I getObject(String criteria) {
       return criteriaToClassMap.get(criteria);
   }

}

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

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