前言
使用Spring,@Autowired注解肯定再熟悉不过了,今天彻底探究一下@Autowired实现的源码细节
实现
其实这个实现方式其实思路很简单:
就是在bean容器中找到type==@Autowired修饰的类型的bean,然后通过反射给属性赋值即可
道理很简单,但还是看代码证实一下,并关注一些实现细节
例子
写一个简单的例子,为方便后续说明
// B Service
@Service
public class BService {
}
// A Service 通过@Autowired依赖注入 B Service
@Service
public class AService {
@Autowired
private BService bService;
}
@Autowired实现步骤
spring内部的默认bean工厂实现为DefaultListableBeanFactory
,然而该BeanFactory并不支持@Autowired注解
实际上@Autowired注解的支持是依靠于ApplicationContext向DefaultListableBeanFactory注册了Autowired后置处理器:AutowiredAnnotationBeanPostProcessor
在bean创建周期的populateBean(填充属性)中会执行该后置处理器的postProcessProperties
方法来完成依赖注入

步骤如下
1.查找带有@Autowired的属性
findAutowiringMetadata
方法查找了当前类属性中带有@Autowired,@Value的属性,包装成InjectionMetadata


其中autowiredAnnotationTypes主要包含两个注解

二.通过beanFactory的resolveDependency
方法获取需要依赖Bean
InjectionMetadata.inject方法中,调用beanFactory的resolveDependency
方法

其中desc即查找的目标,包含了目标的类型
三.给属性赋值
inject方法最终获取到依赖的bean后,反射完成属性赋值

到此,依赖注入的功能就实现了
深入resolveDependency
上面的步骤都很好理解,重点是第二步通过beanFactory的resolveDependency
查找依赖的bean,所以再次深入探究beanFactory是如何获取到依赖的bean的
以上例debugger一下调用resolveDependency
时的参数

beanName为“AService”即被注入的bean, desc中存放BService的一些信息: BService的类型
所以resolveDependency实际上是根据type获取bean,即getBeanByType
,再深入看一下(以下代码都是省略了分支逻辑和缓存逻辑,只保留重点逻辑)
resolveDependency:
public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName, Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
// spring一般doXXX就是实际的主干代码,如createBean和doCreateBean
Object result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
return result;
}
再来doResolveDependency:
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
// 获取依赖的type,使用type去bean容器查找
Class<?> type = descriptor.getDependencyType();
// 查找所有符合的bean
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
// 依赖的beanName
String autowiredBeanName;
// 依赖的bean实体
Object instanceCandidate;
// 一般情况只有一个,但多个符合的也要处理
if (matchingBeans.size() > 1) {
// 从多个里按优先级选择一个,determine即下决定
autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
instanceCandidate = matchingBeans.get(autowiredBeanName);
}
else {
// 只有一个的情况(大部分情况),直接取第一个
Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
autowiredBeanName = entry.getKey();
instanceCandidate = entry.getValue();
}
// 如果返回的是class, 转换为实体
if (instanceCandidate instanceof Class) {
instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
}
// 返回以来的bean实体
Object result = instanceCandidate;
return result;
}
其中重点是:
- findAutowireCandidates:根据type查找依赖注入候选者
- determineAutowireCandidate: 当出现多候选者,选择一个(毕竟依赖注入只能注入一个对象)
findAutowireCandidates
根据type查找依赖注入候选者,先看一下它的定义
protected Map<String, Object> findAutowireCandidates(
@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {
其中:
- beanName:将被填充属性的bean的name
- requiredType:填充的类型,即要查找的依赖
- DependencyDescriptor:依赖的一些描述
- 返回一个Map<String, Object>,即beanName和bean实体的映射map(value不一定都是bean实体,有可能是实体的类),一般情况下返回的map.size==1,但也会有多个的情况
再来看下具体代码
protected Map<String, Object> findAutowireCandidates(
@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {
// 使用BeanFactoryUtils筛选Bean容器中的候选者
String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this, requiredType, true, descriptor.isEager());
// 初始化返回结构
Map<String, Object> result = new LinkedHashMap<>(candidateNames.length);
// 1.从resolvableDependencies中筛选候选者
for (Map.Entry<Class<?>, Object> classObjectEntry : this.resolvableDependencies.entrySet()) {
Class<?> autowiringType = classObjectEntry.getKey();
if (autowiringType.isAssignableFrom(requiredType)) {
Object autowiringValue = classObjectEntry.getValue();
autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType);
if (requiredType.isInstance(autowiringValue)) {
result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue);
break;
}
}
}
// 2.从bean容器中进一步筛选候选者
for (String candidate : candidateNames) {
if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) {
addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
// 返回结果
return result;
}
通过代码可以看出,依赖的候选者来源有两个地方:
- bean容器
- resolvableDependencies
其中bean容器的查找,交给方法BeanFactoryUtils.beanNamesForTypeIncludingAncestors
,那么resolvableDependencies是一个什么东西?
通过查看源码,发现resolvableDependencies也是一个容器,存储的是type->实体的map

再次查找发现容器内容添加基本只有一处,即registerResolvableDependency

registerResolvableDependency是一个public接口,实际上他的存在是为了实现依赖注入非Bean容器中的Bean,可以叫spring托管的外部bean
比如现在又个单例工具对象,你想让其他bean可以依赖注入这个对象,同时又不想把这个对象加入bean容器,则可以使用registerResolvableDependency加入到resolvableDependencies(相当于给spring中加入一个创建好的对象,供其他bean依赖注入,但不需要spring去创建管理它)
再ApplicationContext初始化阶段,会把ApplicationContext对象,BeanFactory对象通过registerResolvableDependency加入到spring中托管

这就是为什么我们的bean能依赖注入上下文对象和bean工厂本身,如下

当然resolvableDependencies依然只是支线逻辑,重点和大部分情况还是从bean容器中查找依赖,即BeanFactoryUtils.beanNamesForTypeIncludingAncestors方法,这个方法返回的是一个字符串数组,也就是beanName的数组,那怎么返回候选项呐?
答案在addCandidateEntry
方法里,看一下它的内部

可以看见它往findAutowireCandidates的result里面的value塞了一个type(Class)而不是bean的实体,这也是为什么上一步doResolveDependency
会有这么一步代码
// 如果返回的是class, 转换为实体
if (instanceCandidate instanceof Class) {
instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
}
所以findAutowireCandidates返回的map可能是beanName->bean实体,也可能是beanName->beanClass
beanNamesForTypeIncludingAncestors
先看下定义
public static String[] beanNamesForTypeIncludingAncestors(
ListableBeanFactory lbf, Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
根据命名:通过type查询beanName数组,参数type即查找的类型,IncludingAncestors
代表如果lbf有父级,要递归去祖先bean工厂中查找,看下代码
public static String[] beanNamesForTypeIncludingAncestors(
ListableBeanFactory lbf, Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
Assert.notNull(lbf, "ListableBeanFactory must not be null");
// 使用beanFactory的getBeanNamesForType方法查找
String[] result = lbf.getBeanNamesForType(type, includeNonSingletons, allowEagerInit);
// 如果有父级,递归查找
if (lbf instanceof HierarchicalBeanFactory) {
HierarchicalBeanFactory hbf = (HierarchicalBeanFactory) lbf;
if (hbf.getParentBeanFactory() instanceof ListableBeanFactory) {
String[] parentResult = beanNamesForTypeIncludingAncestors(
(ListableBeanFactory) hbf.getParentBeanFactory(), type, includeNonSingletons, allowEagerInit);
result = mergeNamesWithParent(result, parentResult, hbf);
}
}
return result;
}
所以其实最核心的方法就是BeanFactory.getBeanNamesForType
,也就是常用的方法getBean(Class<T> requiredType)
内部调用的方法,即根据type在bean容器中获取bean,很好理解,本文就不展开了~
网友评论