旅游网站建设水平评价,门户网站做公众号的好处,两个wordpress如何同步的,WordPress导航菜单无法删除1. 构造方法参数Autowire
BeanClass可以在构造方法上标注Autowired注解#xff0c;Spring在创建Bean实例时将自动为其注入依赖参数#xff1b;Spring会优先使用标注Autowired注解的构造方法#xff1b;当一个构造方法标注了Autowired注解且requiredtrue时#xff0c;其余构…1. 构造方法参数Autowire
BeanClass可以在构造方法上标注Autowired注解Spring在创建Bean实例时将自动为其注入依赖参数Spring会优先使用标注Autowired注解的构造方法当一个构造方法标注了Autowired注解且requiredtrue时其余构造方法不允许再标注Autowired注解当多个构造方法标注了Autowired注解且requiredfalse时它们会成为候选者Spring将选择具有最多依赖项的构造方法如果没有候选者可以满足Spring将使用默认的无参构造方法如果存在如果Class有多个含参构造方法且都没有标注Autowired注解此时在创建Bean时会抛错。
1.1. Spring创建Bean实例
创建Bean实例在AbstractAutowireCapableBeanFactory类的createBeanInstance方法
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {// Make sure bean class is actually resolved at this point.Class? beanClass resolveBeanClass(mbd, beanName);// public和access判断略Supplier? instanceSupplier mbd.getInstanceSupplier();if (instanceSupplier ! null) {return obtainFromSupplier(instanceSupplier, beanName);}// 使用工厂创建Bean实例Bean注解标注的方法会使用这种方式创建Bean实例// 后续有章节进行分析if (mbd.getFactoryMethodName() ! null) {return instantiateUsingFactoryMethod(beanName, mbd, args);}// Shortcut when re-creating the same bean...boolean resolved false;boolean autowireNecessary false;if (args null) {synchronized (mbd.constructorArgumentLock) {if (mbd.resolvedConstructorOrFactoryMethod ! null) {resolved true;autowireNecessary mbd.constructorArgumentsResolved;}}}if (resolved) {if (autowireNecessary) {return autowireConstructor(beanName, mbd, null, null);} else {return instantiateBean(beanName, mbd);}}// 获取候选的构造方法Constructor?[] ctors determineConstructorsFromBeanPostProcessors(beanClass, beanName);if (ctors ! null || mbd.getResolvedAutowireMode() AUTOWIRE_CONSTRUCTOR ||mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {// 使用构造方法创建Bean实例return autowireConstructor(beanName, mbd, ctors, args);}// 此处通过RootBeanDefinition获取候选的构造方法然后创建Bean实例和上面基本一致ctors mbd.getPreferredConstructors();if (ctors ! null) {return autowireConstructor(beanName, mbd, ctors, null);}// 使用默认构造方法创建Bean实例return instantiateBean(beanName, mbd);
}1.2. 获取候选的构造方法集
public Constructor?[] determineCandidateConstructors(Class? beanClass, final String beanName)throws BeanCreationException {// Lets check for lookup methods here...// 略// Quick check on the concurrent map first, with minimal locking.Constructor?[] candidateConstructors this.candidateConstructorsCache.get(beanClass);if (candidateConstructors null) {// Fully synchronized resolution now...synchronized (this.candidateConstructorsCache) {candidateConstructors this.candidateConstructorsCache.get(beanClass);if (candidateConstructors null) {Constructor?[] rawCandidates;try {// 使用java反射获取声明了的所有构造方法rawCandidates beanClass.getDeclaredConstructors();} catch (Throwable ex) {throw new BeanCreationException(beanName,Resolution of declared constructors on bean Class [ beanClass.getName() ] from ClassLoader [ beanClass.getClassLoader() ] failed, ex);}ListConstructor? candidates new ArrayList(rawCandidates.length);// 标注Autowired注解且requiredtrue的构造方法Constructor? requiredConstructor null;// 默认的无参构造方法Constructor? defaultConstructor null;// nullConstructor? primaryConstructor BeanUtils.findPrimaryConstructor(beanClass);int nonSyntheticConstructors 0;for (Constructor? candidate : rawCandidates) {if (!candidate.isSynthetic()) {nonSyntheticConstructors;} else if (primaryConstructor ! null) {continue;}// 在构造方法上查找Autowired注解MergedAnnotation? ann findAutowiredAnnotation(candidate);if (ann ! null) {// 如果之前已经找到了requiredConstructor则抛错if (requiredConstructor ! null) {throw new BeanCreationException(beanName,Invalid autowire-marked constructor: candidate . Found constructor with required Autowired annotation already: requiredConstructor);}boolean required determineRequiredStatus(ann);// 构造方法标注Autowired注解且requiredtrueif (required) {if (!candidates.isEmpty()) {throw new BeanCreationException(beanName,Invalid autowire-marked constructors: candidates . Found constructor with required Autowired annotation: candidate);}requiredConstructor candidate;}// 将构造方法添加到candidates集candidates.add(candidate);} else if (candidate.getParameterCount() 0) {defaultConstructor candidate;}}if (!candidates.isEmpty()) {// 把默认无参构造方法添加到candidates集if (requiredConstructor null) {if (defaultConstructor ! null) {candidates.add(defaultConstructor);}}candidateConstructors candidates.toArray(new Constructor?[0]);} else if (rawCandidates.length 1 rawCandidates[0].getParameterCount() 0) {// 当candidates为空时即所有构造方法都没有标注Autowired注解// 且只有一个构造方法时默认使用这个构造方法candidateConstructors new Constructor?[] {rawCandidates[0]};} else {candidateConstructors new Constructor?[0];}// 维护缓存this.candidateConstructorsCache.put(beanClass, candidateConstructors);}}}return (candidateConstructors.length 0 ? candidateConstructors : null);
}1.3. 使用构造方法创建Bean实例
autowireConstructor(beanName, mbd, ctors, args);autowireConstructor方法
protected BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd, Constructor?[] ctors, Object[] explicitArgs) {return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
}public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,Constructor?[] chosenCtors, Object[] explicitArgs) {BeanWrapperImpl bw new BeanWrapperImpl();this.beanFactory.initBeanWrapper(bw);Constructor? constructorToUse null;ArgumentsHolder argsHolderToUse null;Object[] argsToUse null;// explicitArgs nullif (explicitArgs ! null) {argsToUse explicitArgs;} else {Object[] argsToResolve null;// 获取mbd中缓存的构造方法和参数并用其创建对象此处不详细分析synchronized (mbd.constructorArgumentLock) {constructorToUse (Constructor?) mbd.resolvedConstructorOrFactoryMethod;if (constructorToUse ! null mbd.constructorArgumentsResolved) {argsToUse mbd.resolvedConstructorArguments;if (argsToUse null) {argsToResolve mbd.preparedConstructorArguments;}}}if (argsToResolve ! null) {argsToUse resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);}}// 这里从候选构造方法集选择一个最佳构造方法if (constructorToUse null || argsToUse null) {Constructor?[] candidates chosenCtors;if (candidates null) {// 使用反射获取声明的所有构造方法}// 只有一个无参的默认构造方法// 1. 将其放入mbd缓存起来// 2. 使用这个构造方法创建Bean实例并返回if (candidates.length 1 explicitArgs null !mbd.hasConstructorArgumentValues()) {Constructor? uniqueCandidate candidates[0];if (uniqueCandidate.getParameterCount() 0) {synchronized (mbd.constructorArgumentLock) {mbd.resolvedConstructorOrFactoryMethod uniqueCandidate;mbd.constructorArgumentsResolved true;mbd.resolvedConstructorArguments EMPTY_ARGS;}bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));return bw;}}// Need to resolve the constructor.boolean autowiring (chosenCtors ! null ||mbd.getResolvedAutowireMode() AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);ConstructorArgumentValues resolvedValues null;int minNrOfArgs;if (explicitArgs ! null) {minNrOfArgs explicitArgs.length;} else {ConstructorArgumentValues cargs mbd.getConstructorArgumentValues();resolvedValues new ConstructorArgumentValues();minNrOfArgs resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);}// 排序参数多的排在前面AutowireUtils.sortConstructors(candidates);int minTypeDiffWeight Integer.MAX_VALUE;SetConstructor? ambiguousConstructors null;LinkedListUnsatisfiedDependencyException causes null;for (Constructor? candidate : candidates) {int parameterCount candidate.getParameterCount();if (constructorToUse ! null argsToUse ! null argsToUse.length parameterCount) {// 已经找到了合适的构造方法可以跳出去了break;}if (parameterCount minNrOfArgs) {// 已经找到了合适的构造方法可以跳出去了continue;}ArgumentsHolder argsHolder;Class?[] paramTypes candidate.getParameterTypes();if (resolvedValues ! null) {try {String[] paramNames ConstructorPropertiesChecker.evaluate(candidate, parameterCount);if (paramNames null) {ParameterNameDiscoverer pnd this.beanFactory.getParameterNameDiscoverer();if (pnd ! null) {paramNames pnd.getParameterNames(candidate);}}// 解析构造方法需要的参数argsHolder createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,getUserDeclaredConstructor(candidate), autowiring, candidates.length 1);} catch (UnsatisfiedDependencyException ex) {// Swallow and try next constructor.if (causes null) {causes new LinkedList();}causes.add(ex);continue;}} else {// Explicit arguments given - arguments length must match exactly.if (parameterCount ! explicitArgs.length) {continue;}argsHolder new ArgumentsHolder(explicitArgs);}int typeDiffWeight (mbd.isLenientConstructorResolution() ?argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));// Choose this constructor if it represents the closest match.if (typeDiffWeight minTypeDiffWeight) {constructorToUse candidate;argsHolderToUse argsHolder;argsToUse argsHolder.arguments;minTypeDiffWeight typeDiffWeight;ambiguousConstructors null;} else if (constructorToUse ! null typeDiffWeight minTypeDiffWeight) {if (ambiguousConstructors null) {ambiguousConstructors new LinkedHashSet();ambiguousConstructors.add(constructorToUse);}ambiguousConstructors.add(candidate);}}if (constructorToUse null) {if (causes ! null) {UnsatisfiedDependencyException ex causes.removeLast();for (Exception cause : causes) {this.beanFactory.onSuppressedException(cause);}throw ex;}throw new BeanCreationException(mbd.getResourceDescription(), beanName,Could not resolve matching constructor);} else if (ambiguousConstructors ! null !mbd.isLenientConstructorResolution()) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,Ambiguous constructor matches found in bean);}if (explicitArgs null argsHolderToUse ! null) {argsHolderToUse.storeCache(mbd, constructorToUse);}}// 使用选择到的构造方法创建Bean实例bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));return bw;
}2. 字段和setter方法参数Autowire
2.1. 创建Bean流程
在Bean实例化流程分析时我们了解到在AbstractAutowireCapableBeanFactory类doCreateBean方法会创建Bean实例并进行初始化和依赖注入
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, Nullable Object[] args)throws BeanCreationException {// Instantiate the bean.BeanWrapper instanceWrapper null;if (mbd.isSingleton()) {instanceWrapper this.factoryBeanInstanceCache.remove(beanName);}if (instanceWrapper null) {instanceWrapper createBeanInstance(beanName, mbd, args);}Object bean instanceWrapper.getWrappedInstance();Class? beanType instanceWrapper.getWrappedClass();if (beanType ! NullBean.class) {mbd.resolvedTargetType beanType;}// Allow post-processors to modify the merged bean definition.synchronized (mbd.postProcessingLock) {if (!mbd.postProcessed) {try {applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);} catch (Throwable ex) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,Post-processing of merged bean definition failed, ex);}mbd.postProcessed true;}}// Eagerly cache singletons to be able to resolve circular references// even when triggered by lifecycle interfaces like BeanFactoryAware.boolean earlySingletonExposure (mbd.isSingleton() this.allowCircularReferences isSingletonCurrentlyInCreation(beanName));if (earlySingletonExposure) {addSingletonFactory(beanName, () - getEarlyBeanReference(beanName, mbd, bean));}// Initialize the bean instance.Object exposedObject bean;try {// 依赖注入populateBean(beanName, mbd, instanceWrapper);exposedObject initializeBean(beanName, exposedObject, mbd);} catch (Throwable ex) {if (ex instanceof BeanCreationException beanName.equals(((BeanCreationException) ex).getBeanName())) {throw (BeanCreationException) ex;} else {throw new BeanCreationException(mbd.getResourceDescription(), beanName, Initialization of bean failed, ex);}}// 略return exposedObject;
}protected void populateBean(String beanName, RootBeanDefinition mbd, Nullable BeanWrapper bw) {if (bw null) {if (mbd.hasPropertyValues()) {throw new BeanCreationException(mbd.getResourceDescription(), beanName,Cannot apply property values to null instance);} else {// Skip property population phase for null instance.return;}}// 调用InstantiationAwareBeanPostProcessor处理器postProcessAfterInstantiation方法if (!mbd.isSynthetic() hasInstantiationAwareBeanPostProcessors()) {for (BeanPostProcessor bp : getBeanPostProcessors()) {if (bp instanceof InstantiationAwareBeanPostProcessor) {InstantiationAwareBeanPostProcessor ibp (InstantiationAwareBeanPostProcessor) bp;if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {return;}}}}PropertyValues pvs (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);// 自动注入setter// AUTOWIRE_BY_NAME和AUTOWIRE_BY_TYPE两种模式会进入分支进行处理// 默认AUTOWIRE_NO模式// 此处仅处理有setter方法的属性int resolvedAutowireMode mbd.getResolvedAutowireMode();if (resolvedAutowireMode AUTOWIRE_BY_NAME || resolvedAutowireMode AUTOWIRE_BY_TYPE) {MutablePropertyValues newPvs new MutablePropertyValues(pvs);// 使用属性名称注入if (resolvedAutowireMode AUTOWIRE_BY_NAME) {autowireByName(beanName, mbd, bw, newPvs);}// 使用属性类型注入if (resolvedAutowireMode AUTOWIRE_BY_TYPE) {autowireByType(beanName, mbd, bw, newPvs);}pvs newPvs;}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()) {if (bp instanceof InstantiationAwareBeanPostProcessor) {InstantiationAwareBeanPostProcessor ibp (InstantiationAwareBeanPostProcessor) bp;// 此处调用InstantiationAwareBeanPostProcessor处理器postProcessProperties方法// AutowiredAnnotationBeanPostProcessor实现类中有依赖注入的逻辑PropertyValues 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;}}}if (needsDepCheck) {if (filteredPds null) {filteredPds filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);}checkDependencies(beanName, mbd, filteredPds, pvs);}if (pvs ! null) {applyPropertyValues(beanName, mbd, bw, pvs);}
}2.2. AutowiredAnnotationBeanPostProcessor处理器
此处理器为标注了Autowired的字段和方法进行自动注入。
也会处理Value注解这个暂时不做分析。
2.2.1. postProcessProperties方法
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {// 获取到标注了Autowired注解的字段和方法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;
}private InjectionMetadata findAutowiringMetadata(String beanName, Class? clazz, PropertyValues pvs) {// Fall back to class name as cache key, for backwards compatibility with custom callers.String cacheKey (StringUtils.hasLength(beanName) ? beanName : clazz.getName());// Quick check on the concurrent map first, with minimal locking.InjectionMetadata metadata this.injectionMetadataCache.get(cacheKey);if (InjectionMetadata.needsRefresh(metadata, clazz)) {synchronized (this.injectionMetadataCache) {metadata this.injectionMetadataCache.get(cacheKey);if (InjectionMetadata.needsRefresh(metadata, clazz)) {if (metadata ! null) {metadata.clear(pvs);}// 获取到标注了Autowired注解的字段和方法metadata buildAutowiringMetadata(clazz);this.injectionMetadataCache.put(cacheKey, metadata);}}}return metadata;
}private InjectionMetadata buildAutowiringMetadata(final Class? clazz) {if (!AnnotationUtils.isCandidateClass(clazz, this.autowiredAnnotationTypes)) {return InjectionMetadata.EMPTY;}ListInjectionMetadata.InjectedElement elements new ArrayList();Class? targetClass clazz;do {final ListInjectionMetadata.InjectedElement currElements new ArrayList();ReflectionUtils.doWithLocalFields(targetClass, field - {\// 获取字段上标注的Autowired和Value注解MergedAnnotation? ann findAutowiredAnnotation(field);if (ann ! null) {// 静态字段不处理if (Modifier.isStatic(field.getModifiers())) {return;}boolean required determineRequiredStatus(ann);// 添加到InjectedElement集currElements.add(new AutowiredFieldElement(field, required));}});ReflectionUtils.doWithLocalMethods(targetClass, method - {Method bridgedMethod BridgeMethodResolver.findBridgedMethod(method);if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {return;}MergedAnnotation? ann findAutowiredAnnotation(bridgedMethod);if (ann ! null method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {// 静态方法不处理if (Modifier.isStatic(method.getModifiers())) {return;}boolean required determineRequiredStatus(ann);PropertyDescriptor pd BeanUtils.findPropertyForMethod(bridgedMethod, clazz);currElements.add(new AutowiredMethodElement(method, required, pd));}});elements.addAll(0, currElements);targetClass targetClass.getSuperclass();} while (targetClass ! null targetClass ! Object.class);return InjectionMetadata.forElements(elements, clazz);
}依赖注入
metadata.inject(bean, beanName, pvs);inject的实现在InjectionMetadata类
public void inject(Object target, String beanName, PropertyValues pvs) throws Throwable {CollectionInjectedElement checkedElements this.checkedElements;CollectionInjectedElement elementsToIterate (checkedElements ! null ? checkedElements : this.injectedElements);if (!elementsToIterate.isEmpty()) {for (InjectedElement element : elementsToIterate) {// 调用InjectedElement的inject方法为字段或方法注入依赖// 从之前的方法可以知道element是AutowiredFieldElement或AutowiredMethodElement对象element.inject(target, beanName, pvs);}}
}2.2.2. AutowiredFieldElement类
AutowiredFieldElement的inject方法
protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {Field field (Field) this.member;Object value;if (this.cached) {value resolvedCachedArgument(beanName, this.cachedFieldValue);} else {DependencyDescriptor desc new DependencyDescriptor(field, this.required);desc.setContainingClass(bean.getClass());SetString autowiredBeanNames new LinkedHashSet(1);TypeConverter typeConverter beanFactory.getTypeConverter();try {// 使用beanFactory从容器里面获取依赖的Beanvalue beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);} catch (BeansException ex) {throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(field), ex);}synchronized (this) {if (!this.cached) {Object cachedFieldValue null;if (value ! null || this.required) {cachedFieldValue desc;registerDependentBeans(beanName, autowiredBeanNames);if (autowiredBeanNames.size() 1) {String autowiredBeanName autowiredBeanNames.iterator().next();if (beanFactory.containsBean(autowiredBeanName) beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {cachedFieldValue new ShortcutDependencyDescriptor(desc, autowiredBeanName, field.getType());}}}this.cachedFieldValue cachedFieldValue;this.cached true;}}}if (value ! null) {// 为字段设置值ReflectionUtils.makeAccessible(field);field.set(bean, value);}
}从容器获取依赖的Bean实例
public Object resolveDependency(DependencyDescriptor descriptor, String requestingBeanName,SetString autowiredBeanNames, TypeConverter typeConverter) throws BeansException {descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());if (Optional.class descriptor.getDependencyType()) {return createOptionalDependency(descriptor, requestingBeanName);} else if (ObjectFactory.class descriptor.getDependencyType() ||ObjectProvider.class descriptor.getDependencyType()) {return new DependencyObjectProvider(descriptor, requestingBeanName);} else if (javaxInjectProviderClass descriptor.getDependencyType()) {return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);} else {// 此处处理Lazy注解使用代理// 返回一个代理对象在拦截方法时从容器里面获取真实的Bean实例再调用目标方法// 只是创建代理不做展开分析Object result getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(descriptor, requestingBeanName);if (result null) {// 从容器里面获取依赖的Bean实例result doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);}return result;}
}public Object doResolveDependency(DependencyDescriptor descriptor, String beanName,SetString autowiredBeanNames, TypeConverter typeConverter) throws BeansException {InjectionPoint previousInjectionPoint ConstructorResolver.setCurrentInjectionPoint(descriptor);try {Object shortcut descriptor.resolveShortcut(this);if (shortcut ! null) {return shortcut;}Class? type descriptor.getDependencyType();// 为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) {return (descriptor.getField() ! null ?converter.convertIfNecessary(value, type, descriptor.getField()) :converter.convertIfNecessary(value, type, descriptor.getMethodParameter()));}}// 数组、集合、MapObject multipleBeans resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);if (multipleBeans ! null) {return multipleBeans;}// 根据依赖的数据类型从容器里面查找符合的Bean// BeanName - BeanClass的映射MapString, Object matchingBeans findAutowireCandidates(beanName, type, descriptor);if (matchingBeans.isEmpty()) {if (isRequired(descriptor)) {// 没有找到抛出NoSuchBeanDefinitionException异常raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);}return null;}String autowiredBeanName;Object instanceCandidate;if (matchingBeans.size() 1) {// 当找到多个类型符合的Bean需要选择一个最合适的// 1. 找标注了Primary注解的Bean// 2. 找javax.annotation.Priority配置最高的Bean// 3. 找beanName与字段名相符或bean别名与字段名相符的BeanautowiredBeanName determineAutowireCandidate(matchingBeans, descriptor);if (autowiredBeanName null) {if (isRequired(descriptor) || !indicatesMultipleBeans(type)) {return descriptor.resolveNotUnique(descriptor.getResolvableType(), matchingBeans);} else {return null;}}instanceCandidate matchingBeans.get(autowiredBeanName);} else {// We have exactly one match.Map.EntryString, Object entry matchingBeans.entrySet().iterator().next();autowiredBeanName entry.getKey();instanceCandidate entry.getValue();}if (autowiredBeanNames ! null) {autowiredBeanNames.add(autowiredBeanName);}if (instanceCandidate instanceof Class) {// 使用beanName到容器里面找Bean实例instanceCandidate descriptor.resolveCandidate(autowiredBeanName, type, this);}Object result instanceCandidate;if (result instanceof NullBean) {if (isRequired(descriptor)) {// 没有找到抛出NoSuchBeanDefinitionException异常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);}
}2.2.3. AutowiredMethodElement类
AutowiredMethodElement方法
protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {// pvs包含就不处理if (checkPropertySkipping(pvs)) {return;}Method method (Method) this.member;Object[] arguments;if (this.cached) {arguments resolveCachedArguments(beanName);} else {// 从容器查找依赖的Beanint argumentCount method.getParameterCount();arguments new Object[argumentCount];DependencyDescriptor[] descriptors new DependencyDescriptor[argumentCount];SetString autowiredBeans new LinkedHashSet(argumentCount);TypeConverter typeConverter beanFactory.getTypeConverter();for (int i 0; i arguments.length; i) {MethodParameter methodParam new MethodParameter(method, i);DependencyDescriptor currDesc new DependencyDescriptor(methodParam, this.required);currDesc.setContainingClass(bean.getClass());descriptors[i] currDesc;try {Object arg beanFactory.resolveDependency(currDesc, beanName, autowiredBeans, typeConverter);if (arg null !this.required) {arguments null;break;}arguments[i] arg;} catch (BeansException ex) {throw new UnsatisfiedDependencyException(null, beanName, new InjectionPoint(methodParam), ex);}}synchronized (this) {if (!this.cached) {if (arguments ! null) {DependencyDescriptor[] cachedMethodArguments Arrays.copyOf(descriptors, arguments.length);registerDependentBeans(beanName, autowiredBeans);if (autowiredBeans.size() argumentCount) {IteratorString it autowiredBeans.iterator();Class?[] paramTypes method.getParameterTypes();for (int i 0; i paramTypes.length; i) {String autowiredBeanName it.next();if (beanFactory.containsBean(autowiredBeanName) beanFactory.isTypeMatch(autowiredBeanName, paramTypes[i])) {cachedMethodArguments[i] new ShortcutDependencyDescriptor(descriptors[i], autowiredBeanName, paramTypes[i]);}}}this.cachedMethodArguments cachedMethodArguments;} else {this.cachedMethodArguments null;}this.cached true;}}}if (arguments ! null) {try {// 调用目标方法ReflectionUtils.makeAccessible(method);method.invoke(bean, arguments);} catch (InvocationTargetException ex) {throw ex.getTargetException();}}
}2.3. setter方法Autowire
Spring允许使用setter方法进行依赖注入这种方式需要在注册BeanDefinition时为其指定AutowireMode参数有几个可选的值
AUTOWIRE_NOAUTOWIRE_BY_NAMEAUTOWIRE_BY_TYPEAUTOWIRE_CONSTRUCTORAUTOWIRE_AUTODETECT
例如
GenericBeanDefinition beanDefinition new GenericBeanDefinition();
beanDefinition.setBeanClass(UserService.class);
// 指定使用类型进行依赖注入
beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);registry.registerBeanDefinition(userService, beanDefinition);源码在populateBean流程中这个方法的代码之前记录过此处再看一下setter注入的逻辑
protected void populateBean(String beanName, RootBeanDefinition mbd, Nullable BeanWrapper bw) {// ... 略PropertyValues pvs (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);// 此处处理setter方法注入// 1. 从Bean类型解析property和对应的setter方法将property名称和对应要注入的Bean对象封装到PropertyValues中// 2. 这里有根据属性类型和根据属性名称注入两种模式int resolvedAutowireMode mbd.getResolvedAutowireMode();if (resolvedAutowireMode AUTOWIRE_BY_NAME || resolvedAutowireMode AUTOWIRE_BY_TYPE) {MutablePropertyValues newPvs new MutablePropertyValues(pvs);// Add property values based on autowire by name if applicable.if (resolvedAutowireMode AUTOWIRE_BY_NAME) {autowireByName(beanName, mbd, bw, newPvs);}// Add property values based on autowire by type if applicable.if (resolvedAutowireMode AUTOWIRE_BY_TYPE) {autowireByType(beanName, mbd, bw, newPvs);}pvs newPvs;}boolean hasInstAwareBpps hasInstantiationAwareBeanPostProcessors();boolean needsDepCheck (mbd.getDependencyCheck() ! AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);// 调用InstantiationAwareBeanPostProcessor的postProcessProperties方法// AutowiredAnnotationBeanPostProcessor处理器可以处理Autowired和Value注解前文详细介绍了PropertyDescriptor[] filteredPds null;if (hasInstAwareBpps) {if (pvs null) {pvs mbd.getPropertyValues();}for (BeanPostProcessor bp : getBeanPostProcessors()) {if (bp instanceof InstantiationAwareBeanPostProcessor) {InstantiationAwareBeanPostProcessor ibp (InstantiationAwareBeanPostProcessor) bp;PropertyValues 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;}}}// 默认falseif (needsDepCheck) {if (filteredPds null) {filteredPds filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);}checkDependencies(beanName, mbd, filteredPds, pvs);}// 使用setter方法为属性注入依赖// 不再展开分析if (pvs ! null) {applyPropertyValues(beanName, mbd, bw, pvs);}
}3. Bean方法参数Autowire
3.1. 注册BeanDefinition
private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) {ConfigurationClass configClass beanMethod.getConfigurationClass();MethodMetadata metadata beanMethod.getMetadata();String methodName metadata.getMethodName();AnnotationAttributes bean AnnotationConfigUtils.attributesFor(metadata, Bean.class);// 获取BeanName和别名ListString names new ArrayList(Arrays.asList(bean.getStringArray(name)));String beanName (!names.isEmpty() ? names.remove(0) : methodName);// 注册别名for (String alias : names) {this.registry.registerAlias(beanName, alias);}// 是否覆盖已存在Bean的判断allowBeanDefinitionOverriding属性用于设置是否允许覆盖// 代码略// 创建BeanDefinitionConfigurationClassBeanDefinition beanDef new ConfigurationClassBeanDefinition(configClass, metadata, beanName);beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource()));if (metadata.isStatic()) {// 静态方法if (configClass.getMetadata() instanceof StandardAnnotationMetadata) {beanDef.setBeanClass(((StandardAnnotationMetadata) configClass.getMetadata()).getIntrospectedClass());} else {beanDef.setBeanClassName(configClass.getMetadata().getClassName());}// Bean方法名beanDef.setUniqueFactoryMethodName(methodName);} else {// 实例方法// FactoryBeanName Configuration类的BeanNamebeanDef.setFactoryBeanName(configClass.getBeanName());// Bean方法名beanDef.setUniqueFactoryMethodName(methodName);}if (metadata instanceof StandardMethodMetadata) {beanDef.setResolvedFactoryMethod(((StandardMethodMetadata) metadata).getIntrospectedMethod());}// 设置AutowireMode AUTOWIRE_CONSTRUCTORbeanDef.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);beanDef.setAttribute(org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE);AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata);Autowire autowire bean.getEnum(autowire);if (autowire.isAutowire()) {beanDef.setAutowireMode(autowire.value());}boolean autowireCandidate bean.getBoolean(autowireCandidate);if (!autowireCandidate) {beanDef.setAutowireCandidate(false);}// initMethod及destroyMethod略// Scope及Proxy略this.registry.registerBeanDefinition(beanName, beanDefToRegister);
}3.2. 创建实例
上文介绍过创建Bean实例逻辑在AbstractAutowireCapableBeanFactory类的createBeanInstance方法中其中这段代码用于创建Bean实例
// 使用工厂创建Bean实例Bean注解标注的方法会使用这种方式创建Bean实例
if (mbd.getFactoryMethodName() ! null) {return instantiateUsingFactoryMethod(beanName, mbd, args);
}instantiateUsingFactoryMethod方法
protected BeanWrapper instantiateUsingFactoryMethod(String beanName, RootBeanDefinition mbd, Object[] explicitArgs) {return new ConstructorResolver(this).instantiateUsingFactoryMethod(beanName, mbd, explicitArgs);
}instantiateUsingFactoryMethod方法代码较多此处简单介绍一下流程
从mbd获取factoryBeanName即Configuration类的BeanName并从容器里面获取这个factoryBean对象获取用来创建Bean的Method候选集如果Method候选集只有一个方法且该方法无参数直接使用这个方法创建Bean如果Method候选集有多个方法排序参数多的在前面遍历Method候选集从容器里面获取方法参数Bean选择最优的Method使用最优Method创建Bean。