二、设置Bean属性
收信完注入元数据后,Bean的属性还是没有注入的,还需要将执行属性注入。还是在doCreateBean方法中,收集完注入元数据后,紧接着会调用populateBean:
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);PropertyDescriptor[] filteredPds = null;if (hasInstAwareBpps) {if (pvs == null) {pvs = mbd.getPropertyValues();}for (BeanPostProcessor bp : getBeanPostProcessors()) {// 调用BeanPostProcessorif (bp instanceof InstantiationAwareBeanPostProcessor) {InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;// 调用 postProcessPropertiesPropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);if (pvsToUse == null) {if (filteredPds == null) {filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);}pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);if (pvsToUse == null) {return;}}pvs = pvsToUse;}}}}
可以看到在populateBean中会调用InstantiationAwareBeanPostProcessor.postProcessProperties方法,由于已经知道 AutowiredAnnotationBeanPostProcessor 是实现InstantiationAwareBeanPostProcessor 的,所以可以直接查看实现方法:
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {// 获取缓存中的 InjectionMetadataInjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);try {// 进行属性的注入metadata.inject(bean, beanName, pvs);}// 返回注入的属性return pvs;}// InjectMetadata.javapublic void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {// 获取检查后的元素Collection<InjectedElement> checkedElements = this.checkedElements;// 如果checkedElements不为空就使用checkedElements,否则使用injectedElementsCollection<InjectedElement> elementsToIterate =(checkedElements != null ? checkedElements : this.injectedElements);if (!elementsToIterate.isEmpty()) {// 遍历elementsToIteratefor (InjectedElement element : elementsToIterate) {// AutowiredFieldElement、AutowiredMethodElement这两个类继InjectionMetadata.InjectedElement// 各自重写了inject方法element.inject(target, beanName, pvs);}}}
AutowiredFieldElement#inject
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {// 强转成Field类型Field field = (Field) this.member;Object value;if (this.cached) {// 如果缓存过,直接使用缓存的值,一般第一次注入都是falsevalue = resolvedCachedArgument(beanName, this.cachedFieldValue);}else {// 构建依赖描述符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 {// 进行依赖解决,**********关键代码****见代码片段5value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);}catch (BeansException ex) {throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);}// 加锁synchronized (this) {//....}}// 如果找到了符合的bean,设置字段可访问,利用反射设置值if (value != null) {ReflectionUtils.makeAccessible(field);field.set(bean, value);}}
代码片段5、解决依赖注入resolveDependency
@Override@Nullablepublic 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 {// 判断依赖属性的是否加入了@Lazy注解Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(descriptor, requestingBeanName);if (result == null) {// 解决依赖注入的核心方法,见代码片段6result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);}return result;}}
代码片段6,doResolveDependency
/*** descriptor:依赖描述器,大概描述了 XXX 里的 field 需要自动装配 xxx 类型的 bean* beanName:*/@Nullablepublic Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {// InjectionPointInjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);try {// 1. 快速查找,根据名称查找。AutowiredAnnotationBeanPostProcessor用到Object shortcut = descriptor.resolveShortcut(this);if (shortcut != null) {return shortcut;}// 2. 注入指定值,QualifierAnnotationAutowireCandidateResolver解析@Value会用到Class<?> type = descriptor.getDependencyType();Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);if (value != null) {if (value instanceof String) {// 2.1 占位符解析String strVal = resolveEmbeddedValue((String) value);BeanDefinition bd = (beanName != null && containsBean(beanName) ?getMergedBeanDefinition(beanName) : null);// 2.2 Spring EL 表达式value = evaluateBeanDefinitionString(strVal, bd);}TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());return converter.convertIfNecessary(value, type, descriptor.getTypeDescriptor());}// 3. 集合依赖,如 Array、List、Set、Map。内部查找依赖也是使用findAutowireCandidatesObject multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);if (multipleBeans != null) {return multipleBeans;}// 4. 单个依赖查询*****见代码片段7的解析Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);// 4.1 没有查找到依赖,判断descriptor.requireif (matchingBeans.isEmpty()) {if (isRequired(descriptor)) {raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);}return null;}String autowiredBeanName;Object instanceCandidate;// 4.2 有多个,如何过滤if (matchingBeans.size() > 1) {// 4.2.1 @Primary -> @Priority -> 方法名称或字段名称匹配autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);if (autowiredBeanName == null) {// 4.2.2 根据是否必须,抛出异常。注意这里如果是集合处理,则返回nullif (isRequired(descriptor) || !indicatesMultipleBeans(type)) {return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);}else {return null;}}instanceCandidate = matchingBeans.get(autowiredBeanName);}else {Map.Entry<String, Object> entry = matchingBeans.entrySet().iterator().next();autowiredBeanName = entry.getKey();instanceCandidate = entry.getValue();}// 4.3 到了这,说明有且仅有命中一个if (autowiredBeanNames != null) {autowiredBeanNames.add(autowiredBeanName);}// 4.4 实际上调用 getBean(autowiredBeanName, type)。但什么情况下会出现这种场景?if (instanceCandidate instanceof Class) {// 使用的BeanFactory的getBean的方法。doGetBean()的流程代码instanceCandidate = descriptor.resolveCandidate(autowiredBeanName, type, this);}Object result = instanceCandidate;if (result instanceof NullBean) {if (isRequired(descriptor)) {raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);}result = null;}return result;}finally {ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);}}
说明: doResolveDependency方法的四个功能,快速查找和集合处理都委托给了其它方法,注入指定值虽然看起来复杂,但占位符处理、EL 表达式解析、类型转换这三个功能点都有具体的类处理,也不是本文的重点。
我们重点看一下单个依赖的查询,弄明白了单个依赖的查询,其它集合依赖也差不多。
- 查找容器中所有可用依赖:findAutowireCandidates 方法根据类型查找依赖。
- 如何有多个依赖怎么处理?其实 Spring 有一套通用的流程,先按 @Primary 查找,再按 @Priority,最后按方法名称或字段名称查找,直到只有一个 bean 为止。相关的匹配规则见 determineAutowireCandidate 方法。
- 此时只有一个依赖,从容器获取真实的 bean。
descriptor.resolveCandidate方法根据名称autowiredBeanName实例化对象。
思考:findAutowireCandidates 返回的为什么是对象类型,而不是实例对象?
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
matchingBeans中的 Object 对象可能是对象类型,而不全部是实例对象。因为findAutowireCandidates方法是根据类型 type 查找名称 beanNames,如果容器中该 beanName 还没有实例化,findAutowireCandidates 不会画蛇添足直接实例化该 bean,当然如果已经实例化了会直接返回这个 bean。
代码片段7、findAutowireCandidates
根据上面的分析,resolveDependency方法对Optional、延迟注入、懒加载注入等分别进行了处理。之后 doResolveDependency 在正式查找之前看能不能快速查找,如缓存 beanName、@Value 等快速指定需要注入的值,避免通过类型查找,最后才对集合依赖和单一依赖分别进行了处理。实际上,无论是集合依赖还是单一依赖查找,本质上都是调用 findAutowireCandidates进行类型依赖查找。
从 findAutowireCandidates方法,我们可以看到Spring IoC依赖注入的来源:
- 先查找 Spring IoC 内部依赖
resolvableDependencies。在AbstractApplicationContext#prepareBeanFactory方法中默认设置了如下内部依赖:BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext。 - 在父子容器进行类型查找:查找类型匹配的
beanNames,beanFactory#beanNamesForType方法根据类型查找是,先匹配单例实例类型(包括 Spring 托管 Bean),再匹配 BeanDefinition 的类型。从这一步,我们可以看到 Spring 依赖注入的另外两个来源:一是 Spring 托管的外部 Bean,二是 Spring BeanDefinition。
protected Map<String, Object> findAutowireCandidates(@Nullable String beanName, Class<?> requiredType, DependencyDescriptor descriptor) {Map<String, Object> result = new LinkedHashMap<>(candidateNames.length);// 1. Spring IoC 内部依赖 resolvableDependenciesfor (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. 类型查找:本质上递归调用beanFactory#beanNamesForType。先匹配实例类型,再匹配bd。String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this, requiredType, true, descriptor.isEager());for (String candidate : candidateNames) {// 2.1 如果不是自己依赖自己 , 并且符合装配候选,就塞入result。if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) {// 2.2 添加到候选对象中addCandidateEntry(result, candidate, descriptor, requiredType);}}// 3. 补偿机制:如果依赖查找无法匹配,怎么办?包含泛型补偿和自身引用补偿两种。if (result.isEmpty()) {boolean multiple = indicatesMultipleBeans(requiredType);// 3.1 fallbackDescriptor: 泛型补偿,实际上是允许注入对象类型的泛型存在无法解析的情况DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch();// 3.2 补偿1:不允许自称依赖,但如果是集合依赖,需要过滤非@Qualifier对象。什么场景?for (String candidate : candidateNames) {if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor) &&(!multiple || getAutowireCandidateResolver().hasQualifier(descriptor))) {addCandidateEntry(result, candidate, descriptor, requiredType);}}// 3.3 补偿2:允许自称依赖,但如果是集合依赖,注入的集合依赖中需要过滤自己if (result.isEmpty() && !multiple) {for (String candidate : candidateNames) {if (isSelfReference(beanName, candidate) &&(!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&isAutowireCandidate(candidate, fallbackDescriptor)) {addCandidateEntry(result, candidate, descriptor, requiredType);}}}}return result;}
