目录
前言
关于spring中注入接口类型的List、Map有个比较有意思的点,会自动注入接口的实现类到List、Map中。
例子
首先新建一个接口
public interface Shape {
}
新建两个这个接口的实现类
@Service
public class Rectangle implements Shape {
public Rectangle() {
System.out.println("Rectangle 实例化输出");
}
}
@Service
public class Circle implements Shape {
public Circle() {
System.out.println("Circle实例化输出");
}
}
在另一个类中注入集合
我是在一个启动的runner中注入的:
@Component
@Slf4j
public class TestRunner implements ApplicationRunner {
@Autowired
private List<Shape> services;
@Autowired
private Map<String, Shape> serviceMap;
@Override
public void run(ApplicationArguments args) throws Exception {
for (Shape service : services) {
log.info("++++++++++++++++++++ {}+++++++++++++++++++ ", service.getClass().getName());
}
for (Map.Entry<String, Shape> entry : serviceMap.entrySet()) {
log.info("======================= {} : {} ====================", entry.getKey(), entry.getValue());
}
}
}
注入的结果
如果是List的话,会注入该接口的所有实现类;如果是Map的话,key为类名,value为实现类。