Java 在spring中注入构造函数时,如何知道并注入参数是否为list对象?
我知道如何在工厂模式中注入和使用bean。 在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>
@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知道它是一个列表,因为您将构造函数参数的类型定义为list
- 在任何Springbean中,如果只存在一个构造函数,那么就不需要在构造函数/参数之上编写
,Spring将使用该构造函数自动执行注入@Autowired
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 {
...
}