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();
}
}