Spring按类型自动装配注入数组、集合、Map时,是把应用上下文中对应类型的bean装配进集合,而不是直接查找一个对应类型的集合然后注入。以下面这段代码为例:
-
import org.springframework.beans.factory.annotation.Autowired;
-
import org.springframework.stereotype.Component;
-
-
import java.util.*;
-
-
@Component(
"cdPlayers")
-
public
class CDPlayers {
-
-
@Autowired
-
private MediaPlayer[] mediaPlayerArr;
-
-
@Autowired
-
private List<MediaPlayer> mediaPlayerList;
-
-
@Autowired
-
private Map<String, MediaPlayer> mediaPlayerMap;
-
-
@Autowired
-
public void printInfo() {
-
System.out.println(Arrays.toString(mediaPlayerArr));
-
System.out.println(mediaPlayerList);
-
System.out.println(mediaPlayerMap);
-
}
-
}
Spring会查找应用上下文里可赋给MediaPlayer类型的bean放进mediaPlayerArr数组,查找可赋给MediaPlayer类型的bean放进mediaPlayerList,查找可赋给MediaPlayer类型的bean put进mediaPlayerMap,key为bean的name。
这个过程的源码在DefaultListableBeanFactory的doResolveDependency方法中,具体如下(Spring版本是5.0.2):
-
@Nullable
-
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
-
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter)
throws BeansException {
-
-
InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
-
try {
-
Object shortcut = descriptor.resolveShortcut(
this);
-
if (shortcut !=
null) {
-
return shortcut;
-
}
-
-
Class<?> type = descriptor.getDependencyType();