一、引言
Spring是支持基于接口实现类的直接注入的。支持注入Map,List等集合中。
二、适用场景(策略模式)
- 适用于一个接口有多个实现类,然后根据不同的参数选择执行不同的实现类。
- 对于Map类型,Spring 会在启动时,自动查找实现了该接口的 bean,放到这个Map中去。 key为bean的名字,value为实现了该接口的bean。需要注意的是只有在Map的key为String类型时才有效。
三、具体代码
public interface SuperService {
}
@Service
public interface SubAService implement SuperService {
}
@Service
public interface SubBService implement SuperService {
}
@Autowired
Map<String,SuperService> map;
@Autowired
List<SuperService> list;