从上次分析@Autowired和@Resource注解源码分析中预留了一个问题,其在第一阶段已经将注解信息封装在了InjectionMetadata数据中,
在第二阶段将根据InjectionMetadata数据进行一系列的依赖注入,今天就接着开始从这里分析吧~
上篇文章对@Autowired和@Resource的源码分析
先来看看一个小例子
public class AnnotationDependencyInjectionResolutionDemo {
@Autowired
@Lazy
private User user;
@Autowired
private Map<String, User> userMap; // 集合类型注入
@Autowired
private Optional<User> userOptional;
@Autowired
private ObjectFactory<User> objectFactory; // 这里也是懒加载过程
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(AnnotationDependencyInjectionResolutionDemo.class);
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(applicationContext);
String xmlResourcePath = "classpath:META-INF/dependency-lookup-context.xml";
beanDefinitionReader.loadBeanDefinitions(xmlResourcePath);
applicationContext.refresh();
// 依赖查找
AnnotationDependencyInjectionResolutionDemo bean = applicationContext.getBean(
AnnotationDependencyInjectionResolutionDemo.class);
System.out.println(bean.user);
System.out.println(bean.userMap);
System.out.println(bean.userOptional);
System.out.println(bean.objectFactory.getObject());
applicationContext.close();
}
}
//
//
xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.braden.entity.User">
<property name="name" value="braden"/>
<property name="sex" value="male"/>
<property name="age" value="18"/>
</bean>
<bean id="superUser" class="com.braden.entity.SupperUser" primary="true">
<property name="name" value="dw"/>
<property name="sex" value="male"/>
<property name="age" value="22"/>
<property name="address" value="上海市浦东新区"/>
</bean>
</beans>
通过调用栈来看看依赖处理入口
可以看到正好衔接上篇文章中postProcessProperties后处理器进行依赖注入阶段…
再来回顾下源码:
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
// 首次在postProcessMergedBeanDefinition中处理了元信息后 在这里直接从缓存中拿取
InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
try {
metadata.inject(bean, beanName, pvs);
}
catch (BeanCreationException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
}
return pvs;
}
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Collection<InjectedElement> checkedElements = this.checkedElements;
Collection<InjectedElement> elementsToIterate =
(checkedElements != null ? checkedElements : this.injectedElements);
// 一个注解就相当于一个InjectedElement
if (!elementsToIterate.isEmpty()) {
for (InjectedElement element : elementsToIterate) {
if (logger.isTraceEnabled()) {
logger.trace("Processing injected element of bean '" + beanName + "': " + element);
}
// 这里开始注入..
// AutowiredAnnotationBeanPostProcessor提供了两种实现,
// 分别是基于方法和属性字段
element.inject(target, beanName, pvs);
}
}
}
//
//
//
AutowiredAnnotationBeanPostProcessor提供了两种注入实现,分别是基于方法和属性字段,两种实现上类似,我们就以属性字段为例~
// AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement#inject
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
Field field = (Field) this.member;
Object value;
// 如果之前解析过,也就是缓存字段有,那就之前从缓存中取了
if (this.cached) {
value = resolvedCachedArgument(beanName, this.cachedFieldValue);
}
else {
// 依赖描述符,封装当前被注入的bean的类信息,待注入的字段、方法等信息
DependencyDescriptor desc = new DependencyDescriptor(field, this.required);
desc.setContainingClass(bean.getClass());
Set<String> autowiredBeanNames = new LinkedHashSet<>(1);
Assert.state(beanFactory != null, "No BeanFactory available");
// 类型转换器
TypeConverter typeConverter = beanFactory.getTypeConverter();
try {
// 这里便是真正的依赖处理过程执行入口
value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);
}
// 这里把得到的bean信息缓存起来
synchronized (this) {
if (!this.cached) {
if (value != null || this.required) {
this.cachedFieldValue = desc;
registerDependentBeans(beanName, autowiredBeanNames);
if (autowiredBeanNames.size() == 1) {
String autowiredBeanName = autowiredBeanNames.iterator().next();
if (beanFactory.containsBean(autowiredBeanName) &&
beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
this.cachedFieldValue = new ShortcutDependencyDescriptor(
desc, autowiredBeanName, field.getType());
}
}
}
else {
this.cachedFieldValue = null;
}
this.cached = true;
}
}
}
if (value != null) {
ReflectionUtils.makeAccessible(field);
field.set(bean, value);
}
}
}
//
//
//
简单的说这段方法先判断是否已经解析,如果已经解析了就直接从缓存中取即可,不然就将解析过程委托给DefaultListableBeanFactory#resolveDependency处理,
然后将解析的后的值缓存起来,下次使用直接从缓存中取即可.
DefaultListableBeanFactory#resolveDependency
依赖处理过程的真正入口方法,也是本文的核心
// 依赖处理过程 基础入口
@Override
@Nullable
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
// 处理Optional类型的注入
if (Optional.class == descriptor.getDependencyType()) {
return createOptionalDependency(descriptor, requestingBeanName);
}
// 处理ObjectFactory类的注入
else if (ObjectFactory.class == descriptor.getDependencyType() ||
ObjectProvider.class == descriptor.getDependencyType()) {
return new DependencyObjectProvider(descriptor, requestingBeanName);
}
// 对jsr330类型的支持
else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
}
else {
// 如果设置了懒加载模式,就暂时返回代理对象(这里暂时没有进行依赖处理)
Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
descriptor, requestingBeanName);
if (result == null) {
// 核心方法,上面的各种条件判断,最终都是通过doResolveDependency方法处理,只不过是需要做一些封装罢了
result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
}
return result;
}
}
//
//
//
//
支持Optional、延迟注入、懒加载注入、正常注入
抛开条件判断,可以看到真正核心做事的是DefaultListableBeanFactory#doResolveDependency,不管是Optional类型还是ObjectFactory类型
底层都是通过doResolveDependency方法来进行依赖处理的,只不过是需要做一些封装罢了,来看看它们怎么封装的…
/**
* Create an {@link Optional} wrapper for the specified dependency.
*/
// 做一层包装
private Optional<?> createOptionalDependency(
DependencyDescriptor descriptor, @Nullable String beanName, final Object... args) {
DependencyDescriptor descriptorToUse = new NestedDependencyDescriptor(descriptor) {
@Override
public boolean isRequired() {
return false;
}
@Override
public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory) {
return (!ObjectUtils.isEmpty(args) ? beanFactory.getBean(beanName, args) :
super.resolveCandidate(beanName, requiredType, beanFactory));
}
};
// 最终还是它
Object result = doResolveDependency(descriptorToUse, beanName, null, null);
return (result instanceof Optional ? (Optional<?>) result : Optional.ofNullable(result));
}
/**
* Serializable ObjectFactory/ObjectProvider for lazy resolution of a dependency.
*/
// 懒加载
private class DependencyObjectProvider implements BeanObjectProvider<Object> {
private final DependencyDescriptor descriptor;
private final boolean optional;
@Nullable
private final String beanName;
public DependencyObjectProvider(DependencyDescriptor descriptor, @Nullable String beanName) {
this.descriptor = new NestedDependencyDescriptor(descriptor);
this.optional = (this.descriptor.getDependencyType() == Optional.class);
this.beanName = beanName;
}
@Override
public Object getObject() throws BeansException {
if (this.optional) {
return createOptionalDependency(this.descriptor, this.beanName);
}
else {
// 最终还是它,只不过是在需要的时候才调用getObject进行依赖查找
Object result = doResolveDependency(this.descriptor, this.beanName, null, null);
if (result == null) {
throw new NoSuchBeanDefinitionException(this.descriptor.getResolvableType());
}
return result;
}
}
//
//
//
//
//
//
DefaultListableBeanFactory#doResolveDependency
这一方法才是真正开始依赖处理,并执行依赖属性的注入
@Nullable
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
// 多次注入 嵌套保护点
// 试想在一个线程内部有多层次调用,如何来记录当前的注入点呢?
// 这里使用ThreadLocal实现,看看finally还原的过程,简单的说就是 进来的时候是什么值,走的时候就是什么值(就是设置回去)
// 这样做的原因是因为在其他的地方有使用InjectionPoint这个值
InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
try {
Object shortcut = descriptor.resolveShortcut(this);
if (shortcut != null) {
return shortcut;
}
// 所需要注入的属性字段的类型
Class<?> type = descriptor.getDependencyType();
// 用于支持Spring中新增的注解@Value
Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
if (value != null) {
if (value instanceof String) {
String strVal = resolveEmbeddedValue((String) value);
BeanDefinition bd = (beanName != null && containsBean(beanName) ?
getMergedBeanDefinition(beanName) : null);
value = evaluateBeanDefinitionString(strVal, bd);
}
TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
try {
return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());
}
catch (UnsupportedOperationException ex) {
// A custom TypeConverter which does not support TypeDescriptor resolution...
return (descriptor.getField() != null ?
converter.convertIfNecessary(value, type, descriptor.getField()) :
converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));
}
}
// 处理数组,集合,map这样多个bean的属性
Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
if (multipleBeans != null) {
return multipleBeans;
}
// beanName 被注入的bean
// matchingBeans表示是的是根据descriptor找到的符合条件的待注入目标bean的实例对象
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
if (matchingBeans.isEmpty()) {
// 也就是此属性是否必须的,如果是的话,这里又没有找到可用的待注入的bean,那就会抛异常处理
if (isRequired(descriptor)) {
raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
}
return null;
}
String autowiredBeanName;
Object instanceCandidate;
// 如果匹配的bean有多个,那就从候选集合中选择一个
if (matchingBeans.size() > 1) {
autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
if (autowiredBeanName == null) {
// 如果没有找到合适的,那就是在多个可选的情况下,没有设定优先条件
if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {
return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);
}
else {
// In case of an optional Collection/Map, silently ignore a non-unique case:
// possibly it was meant to be an empty collection of multiple regular beans
// (before 4.3 in particular when we didn't even look for collection beans).
return null;
}
}
// 说明通过determineAutowireCandidate选好了一个
instanceCandidate = matchingBeans.get(autowiredBeanName);
}
else {
// We have exactly one match.
// 刚刚好,就一个满足条件的
Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();
autowiredBeanName = entry.getKey();
instanceCandidate = entry.getValue();
}
if (autowiredBeanNames != null) {
autowiredBeanNames.add(autowiredBeanName);
}
// 如果是Class类型的实例,那就需要通过它找到对应类型的具体实例
if (instanceCandidate instanceof Class) {
instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);
}
Object result = instanceCandidate;
if (result instanceof NullBean) {
if (isRequired(descriptor)) {
raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
}
result = null;
}
if (!ClassUtils.isAssignableValue(type, result)) {
throw new BeanNotOfRequiredTypeException(autowiredBeanName, type, instanceCandidate.getClass());
}
return result;
}
finally {
ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
}
}
static InjectionPoint setCurrentInjectionPoint(@Nullable InjectionPoint injectionPoint) {
InjectionPoint old = currentInjectionPoint.get();
if (injectionPoint != null) {
currentInjectionPoint.set(injectionPoint);
}
else {
currentInjectionPoint.remove();
}
return old;
}
//
//
//
//
//
//
doResolveDependency主要做的几件事:
- 对Spring中新增的注解@Value的支持,如果注解类型是@Value,则直接通过相关方法处理 返回
- 如果依赖的是数组,集合,map等这样多个bean的属性,那就委托给resolveMultipleBeans方法把它解析出来
- 如果以上两个都不是,那就是普通的单依赖属性,通过findAutowireCandidates找到,可能有多个都符合条件,
那就通过determineAutowireCandidate来选择一个返回
DefaultListableBeanFactory#resolveMultipleBeans
最终还是通过findAutowireCandidates来处理,只不过在返回之前进行了类型转换
@Nullable
private Object resolveMultipleBeans(DependencyDescriptor descriptor, @Nullable String beanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) {
final Class<?> type = descriptor.getDependencyType();
if (descriptor instanceof StreamDependencyDescriptor) {
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
if (autowiredBeanNames != null) {
autowiredBeanNames.addAll(matchingBeans.keySet());
}
Stream<Object> stream = matchingBeans.keySet().stream()
.map(name -> descriptor.resolveCandidate(name, type, this))
.filter(bean -> !(bean instanceof NullBean));
if (((StreamDependencyDescriptor) descriptor).isOrdered()) {
stream = stream.sorted(adaptOrderComparator(matchingBeans));
}
return stream;
}
// 如果是数组
else if (type.isArray()) {
Class<?> componentType = type.getComponentType();
ResolvableType resolvableType = descriptor.getResolvableType();
Class<?> resolvedArrayType = resolvableType.resolve(type);
if (resolvedArrayType != type) {
componentType = resolvableType.getComponentType().resolve();
}
if (componentType == null) {
return null;
}
// 根据属性类型找到IOC容器中所有类型匹配的bean
// 其中key是beanName
// value是通过getBean(beanName)返回的实例
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, componentType,
new MultiElementDescriptor(descriptor));
if (matchingBeans.isEmpty()) {
return null;
}
if (autowiredBeanNames != null) {
autowiredBeanNames.addAll(matchingBeans.keySet());
}
TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
// 通过转换器将bean的值转化为对应的type类型
Object result = converter.convertIfNecessary(matchingBeans.values(), resolvedArrayType);
if (result instanceof Object[]) {
Comparator<Object> comparator = adaptDependencyComparator(matchingBeans);
if (comparator != null) {
Arrays.sort((Object[]) result, comparator);
}
}
return result;
}
// type是集合类型
else if (Collection.class.isAssignableFrom(type) && type.isInterface()) {
Class<?> elementType = descriptor.getResolvableType().asCollection().resolveGeneric();
if (elementType == null) {
return null;
}
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, elementType,
new MultiElementDescriptor(descriptor));
if (matchingBeans.isEmpty()) {
return null;
}
if (autowiredBeanNames != null) {
autowiredBeanNames.addAll(matchingBeans.keySet());
}
TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
Object result = converter.convertIfNecessary(matchingBeans.values(), type);
if (result instanceof List) {
Comparator<Object> comparator = adaptDependencyComparator(matchingBeans);
if (comparator != null) {
((List<?>) result).sort(comparator);
}
}
return result;
}
// type是Map类型
else if (Map.class == type) {
// 拿到key/value的具体类型
ResolvableType mapType = descriptor.getResolvableType().asMap();
Class<?> keyType = mapType.resolveGeneric(0);
if (String.class != keyType) {
return null;
}
Class<?> valueType = mapType.resolveGeneric(1);
if (valueType == null) {
return null;
}
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, valueType,
new MultiElementDescriptor(descriptor));
if (matchingBeans.isEmpty()) {
return null;
}
if (autowiredBeanNames != null) {
autowiredBeanNames.addAll(matchingBeans.keySet());
}
return matchingBeans;
}
else {
return null;
}
}
//
//
//
//
//
//
DefaultListableBeanFactory#findAutowireCandidates
这里便是通过指定类型requiredType找到满足添加的候选集合
protected Map<String, Object> findAutowireCandidates(
@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {
// 管理的bean, 有顺序, 先到先注册
// 把类型匹配的bean都找出来,该方法除了当前beanFactory还会递归对父parentFactory进行查找
String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this, requiredType, true, descriptor.isEager());
Map<String, Object> result = new LinkedHashMap<>(candidateNames.length);
// Spring IOC内部依赖的resolvableDependencies
// 也就是非Spring容器管理对象
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;
}
}
}
// 把满足条件的beanName对应的bean都找出来
for (String candidate : candidateNames) {
// isSelfReference说明beanName和candidate本质是同一个对象
// isAutowireCandidate进一步匹配bd.autowireCandidate、泛型、@Qualifier等进行过滤
if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) {
addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
// 结果集为空&注入属性是非数组、容器类型
// 补偿机制,泛型补偿,和自引用补偿
if (result.isEmpty()) {
boolean multiple = indicatesMultipleBeans(requiredType);
// Consider fallback matches if the first pass failed to find anything...
// FallbackMatch:放宽对泛型类型的验证
DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch();
for (String candidate : candidateNames) {
if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor) &&
(!multiple || getAutowireCandidateResolver().hasQualifier(descriptor))) {
addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
if (result.isEmpty() && !multiple) {
// Consider self references as a final pass...
// but in the case of a dependency collection, not the very same bean itself.
// 如果结果还是为空,Spring会尝试将自引用添加到结果中
for (String candidate : candidateNames) {
if (isSelfReference(beanName, candidate) &&
(!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
isAutowireCandidate(candidate, fallbackDescriptor)) {
addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
}
}
return result;
}
//
//
//
//
//
依赖注入来源
- BeanDefinition 注册
- 单例对象注入
- 非Spring容器管理bean,resolvableDependencies
通过findAutowireCandidates会从这三个来源进行依赖查找,如果仍然无法找到依赖对象,会进行一些补偿机制,如泛型补偿、自引用补偿
DefaultListableBeanFactory#addCandidateEntry
通过依赖查找将查找成功的bean添加到候选集合中
private void addCandidateEntry(Map<String, Object> candidates, String candidateName,
DependencyDescriptor descriptor, Class<?> requiredType) {
if (descriptor instanceof MultiElementDescriptor) {
// 最终还是通过getBean找到依赖的bean
Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this);
if (!(beanInstance instanceof NullBean)) {
candidates.put(candidateName, beanInstance);
}
}
else if (containsSingleton(candidateName) || (descriptor instanceof StreamDependencyDescriptor &&
((StreamDependencyDescriptor) descriptor).isOrdered())) {
Object beanInstance = descriptor.resolveCandidate(candidateName, requiredType, this);
candidates.put(candidateName, (beanInstance instanceof NullBean ? null : beanInstance));
}
else {
candidates.put(candidateName, getType(candidateName));
}
}
// DependencyDescriptor#resolveCandidate
public Object resolveCandidate(String beanName, Class<?> requiredType, BeanFactory beanFactory)
throws BeansException {
return beanFactory.getBean(beanName);
}
//
//
//
//
//
终于,经过重重验证、判断,最终还是通过getBean的方式依赖查找,然后将查询的结果返回~
determineAutowireCandidate
候选集如果有多个可以的实例,则根据primary, priority等选择一个
protected String determineAutowireCandidate(Map<String, Object> candidates, DependencyDescriptor descriptor) {
Class<?> requiredType = descriptor.getDependencyType();
// 找到primary bean
String primaryCandidate = determinePrimaryCandidate(candidates, requiredType);
if (primaryCandidate != null) {
return primaryCandidate;
}
// 按照优先级来
String priorityCandidate = determineHighestPriorityCandidate(candidates, requiredType);
if (priorityCandidate != null) {
return priorityCandidate;
}
// Fallback
// 尝试从非Spring IOC管理的resolvableDependencies中找(内部对象)
for (Map.Entry<String, Object> entry : candidates.entrySet()) {
String candidateName = entry.getKey();
Object beanInstance = entry.getValue();
if ((beanInstance != null && this.resolvableDependencies.containsValue(beanInstance)) ||
matchesBeanName(candidateName, descriptor.getDependencyName())) {
return candidateName;
}
}
return null;
}
//
//
//
//
以上是个人理解,如有问题请指出,谢谢!