spring bean 的集合注入

1,664 阅读1分钟

一,前置

@Autowired
private List<IUserService> list;
@Autowired
private Map<String,IUserService> map;

map中自动注入了IUserService相关的两个实现类 image.png 像这种很多同学都会问,这是怎么实现的?在哪里搞了配置还是重写了什么相关方法,才将对应接口的实现类给注入到Map或者List集合里面了呢? 其实呢,spring框架已经帮我们封装好了,我们不需要额外的操作.

二,原理

当spring 扫描@Autowired 注解的时候,会在当前类通过反射的形式注入对应的bean,当为集合时则是通过类型查找的方式注入bean集合.

三,源码

入口 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject

image.png 继续 org.springframework.beans.factory.support.DefaultListableBeanFactory#resolveDependency

image.png

深入 org.springframework.beans.factory.support.DefaultListableBeanFactory#doResolveDependency

image.png

目标方法 org.springframework.beans.factory.support.DefaultListableBeanFactory#resolveMultipleBeans 数组 相关实现

image.png

List 相关实现

image.png

Map 相关实现

image.png

总结

学无止境,只有理解底层和深入分析源码才能更好的使用。