问题描述
我知道如何在工厂模式中注入和使用 bean。 spring注入构造函数时,如何知道并注入参数是否为列表对象?
@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);
}
}
示例处理程序使用 3 个 bean 创建,如下所示。
@Component
public class SampleHandlerA implements SampleHandler {
...
}
@Component
public class SampleHandlerB implements SampleHandler {
...
}
@Component
public class SampleHandlerC implements SampleHandler {
...
}
解决方法
- 您的问题:“如果参数是列表对象,您如何知道并注入?”
- 如果您想知道何时使用列表,当您看到多个相同类型的 bean 的可能性时,您应该使用列表/集合。
- 如果您不确定该 bean 是否会出现在上下文中,那么您应该使用 Optional
- 您在代码中的问题:“spring 如何知道这里并将其注入列表?”
- Spring 知道它是一个列表,因为您将构造函数参数的类型定义为 List
- 在任何 Spring bean 中,如果只存在一个构造函数,则无需在构造函数/参数之上编写
@Autowired
,Spring 将使用该构造函数自动进行注入。docs