spring自动注入可使用List、Map类型来接收多个实现类
自定义接口TestInterface
public interface TestInterface {
void say();
}
实现类TestA
public class TestA implements TestInterface {
@Override
public void say() {
System.out.println("this is TestA");
}
}
实现类TestB
public class TestB implements TestInterface {
@Override
public void say() {
System.out.println("this is TestB");
}
}
测试
@Resource
private List<TestInterface> interfaceList;
@Resource
private Map<String, TestInterface> interfaceHashMap;
interfaceList.forEach(TestInterface::say);
System.out.println("================================");
for(Map.Entry<String, TestInterface> entry : interfaceHashMap.entrySet()){
System.out.println(entry.getKey());
entry.getValue().say();
}
List集合会接受所有TestInterface接口的实现类
Map集合会接受所有TestInterface接口的实现类,key则为bean name,默认为第一个字母小写的类名
遍历结果为
this is TestA
this is TestB
================================
testA
this is TestA
testB
this is TestB