Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在spring中注入构造函数时,如何知道并注入参数是否为list对象?_Java_Spring_Constructor Injection - Fatal编程技术网

Java 在spring中注入构造函数时,如何知道并注入参数是否为list对象?

Java 在spring中注入构造函数时,如何知道并注入参数是否为list对象?,java,spring,constructor-injection,Java,Spring,Constructor Injection,我知道如何在工厂模式中注入和使用bean。 在spring中注入构造函数时,如何知道并注入参数是否为list对象 @Component public class SampleFactory { private final Map<SampleType, SampleHandler> sampleHandlerMap = new ConcurrentHashMap<>(); public SampleFactory(List<SampleHandler>

我知道如何在工厂模式中注入和使用bean。 在spring中注入构造函数时,如何知道并注入参数是否为list对象

@Component
public class SampleFactory {
  private final Map<SampleType, SampleHandler> sampleHandlerMap = new ConcurrentHashMap<>();

  public SampleFactory(List<SampleHandler> sampleHandlers) { // How does spring know here and inject it into a list?
    if(CollectionUtils.isEmpty(sampleHandlers)) {
      throw new IllegalArgumentException("No sampleHandler exists");
    }

    for (SampleHandler sampleHandler: sampleHandlers) {
      this.sampleHandlerMap.put(sampleHandler.getSampleType, sampleHandler);
    }
  }

  public SampleHandler getHandler(SampleType sampleType) {
    return sampleHandlerMap.get(sampleType);
  }
}
  • 您的问题:“如果参数是列表对象,您如何知道并注入?”
    • 若您想知道何时使用list,当您看到可能存在多个相同类型的bean时,应该使用list/collection
    • 如果您不确定该bean是否会出现在上下文中,那么应该使用可选的
  • 您在代码中的问题:“spring如何知道这里并将其注入列表?”
    • Spring知道它是一个列表,因为您将构造函数参数的类型定义为list
    • 在任何Springbean中,如果只存在一个构造函数,那么就不需要在构造函数/参数之上编写
      @Autowired
      ,Spring将使用该构造函数自动执行注入

  • Spring具有特定的逻辑,可以识别
    集合
    列表
    、或
    集合
    ,并将其解释为“可能有多个bean匹配,所以将它们全部给我”。您的问题是什么?Spring是如何实现的?3实现SampleHandler的代码被创建为List,Spring是否将该List注入构造函数?所有实现SampleHandler的Spring bean都将被注入该列表。
    @Component
    public class SampleHandlerA implements SampleHandler {
       ...
    }
    
    @Component
    public class SampleHandlerB implements SampleHandler {
       ...
    }
    
    @Component
    public class SampleHandlerC implements SampleHandler {
       ...
    }