Spring的接口集合注入功能
对于Spring中已经注入的bean, 可以使用Autowired, 通过Map<String, BeanInterface>或List<BeanInterface>的方式直接注入
实现步骤
- 定义一个接口
 - 实现这个接口的一系列类, 都加上 @Component 或者 @Service 注解, 使其成为 spring bean
 - 在其他类中, 通过 
@Autowired private Map<String, InterfaceName> interfaceMap;或@Autowired private List<InterfaceName> interfaceList;可以得到上面定义的类的bean映射或列表- 对于Map, Spring会将实例化的bean放入value, key则为bean的名称
 - 对于List,列表就是实例化的bean
 
 - 如果要控制list中的顺序, 在实现类中加入@Order(value) 注解, 值越小越先被初始化越先被放入List
 
验证
先定义一个接口
public interface GenericService {
    void breath();
}
 
然后定义接口的实现类
// Dog.java
@Service("dog-control")
public class Dog implements GenericService {
    @Override
    public void breath() {
        System.out.println("dog breath");
    }
}
//Cat.java
@Component
public class Cat implements GenericService {
    @Override
    public void breath() {
        System.out.println("cat breath");
    }
}
 
在Demo类中引用
@Component
public class Demo {
    @Autowired
    private Map<String,GenericService> GenericServiceMap;
    @Autowired
    private List<GenericService> GenericServiceList;
    public void dogBreath() {
        this.GenericServiceMap.get("dog-control").breath();
    }
    public void firstBreath() {
        this.GenericServiceList.get(0).breath();
    }
}
 
测试用例
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplicationTests {
    @Autowired
    private com.service.Demo demo;
    @Test
    public  void testMap(){
        demo.dogBreath();
    }
    @Test
    public  void testList(){
        demo.firstBreath();
    }
}










