Spring IOC源码:简单易懂的Spring IOC 思路介绍
Spring IOC源码:核心流程介绍
Spring IOC源码:ApplicationContext刷新前准备工作
Spring IOC源码:obtainFreshBeanFactory 详解(上)
Spring IOC源码:obtainFreshBeanFactory 详解(中)
Spring IOC源码:obtainFreshBeanFactory 详解(下)
Spring IOC源码:<context:component-scan>源码详解
Spring IOC源码:invokeBeanFactoryPostProcessors 后置处理器详解
Spring IOC源码:registerBeanPostProcessors 详解
Spring IOC源码:实例化前的准备工作
Spring IOC源码:finishBeanFactoryInitialization详解
Spring IoC源码:getBean 详解
Spring IoC源码:createBean( 上)
Spring IoC源码:createBean( 中)
Spring IoC源码:createBean( 下)
Spring IoC源码:finishRefresh 完成刷新详解
上篇文章讲解了Bean的实例化过程,包含构造器的选择、参数的创建等,本篇继续创建createBean的剩余流程,包括Bean实例化后的初始化属性注入工作,以及BeanPostProcessor的执行过程。
正文上篇文章讲解了createBeanInstance(beanName, mbd, args)方法的流程,这节继续讲解后续内容。
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {//如果是单例并且是FactoryBean则尝试移除
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) { //创建Bean实例,通过策略进行创建,如果选择有参构造或无参构造
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
//获取当前实例对象
final Object bean = instanceWrapper.getWrappedInstance();
//当前实例的Calss对象
Class>beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) { //设置当前bean定义信息的目标类型
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try {//执行MergedBeanDefinitionPostProcessor类型后置处理器的postProcessMergedBeanDefinition方法,
//如@Autowire注解,就是通过该后置处理器进行解析
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.
//如果是单例,允许循环依赖,并且beanName正在创建中
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
//包装成FactoryObject对象,并添加到三级缓存中
addSingletonFactory(beanName, () ->getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try { //初始化过程,进行属性注入。该过程递归创建其依赖的属性。如果A中有B,B中有C,则创建B跟C。
populateBean(beanName, mbd, instanceWrapper);
//该过程执行后置处理器的before方法,bean的init方法,后置处理器的after方法,可能会生成新的bean对象
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);
}
}
if (earlySingletonExposure) { //从缓存中获取,因为上面我们将其添加到三级缓存中,从三级缓存中获取会调用FactoryObject对象的getObject方法,可能会触发AOP代理。返回代理对象
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) { //如果bean对象还是原来的,则将三级缓存中获取的对象赋值过去
if (exposedObject == bean) {exposedObject = earlySingletonReference;
}
//如果exposedObject在initializeBean方法中被增强 && 不允许在循环引用的情况下使用注入原始bean实例
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {// 获取依赖当前beanName的所有bean名称
String[] dependentBeans = getDependentBeans(beanName);
SetactualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
//尝试移除这些bean的实例,因为这些bean依赖的bean已经被增强了,他们依赖的bean相当于脏数据
for (String dependentBean : dependentBeans) {if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try { //注册用于销毁的bean,执行销毁操作的有三种:自定义destroy方法、DisposableBean接口、DestructionAwareBeanPostProcessor
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) { throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName),见方法1详解
addSingletonFactory(beanName, () ->getEarlyBeanReference(beanName, mbd, bean)),见方法2详解
populateBean(beanName, mbd, instanceWrapper),见方法3详解
方法1:applyMergedBeanDefinitionPostProcessorsprotected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class>beanType, String beanName) {for (BeanPostProcessor bp : getBeanPostProcessors()) { //执行类型为MergedBeanDefinitionPostProcessor的后置处理器,@Autowire注解就是在这块解析的
if (bp instanceof MergedBeanDefinitionPostProcessor) { MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
方法2:addSingletonFactoryprotected void addSingletonFactory(String beanName, ObjectFactory>singletonFactory) {Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) { //如果一级缓存中不存在该对象
if (!this.singletonObjects.containsKey(beanName)) { //往三级缓存中存入类型为ObjectFactory的工厂对象
this.singletonFactories.put(beanName, singletonFactory);
//移除二级缓存
this.earlySingletonObjects.remove(beanName);
//将beanName添加到注册缓存中
this.registeredSingletons.add(beanName);
}
}
}
三级缓存中我们存入的是工厂对象,我们知道工厂对象要获取实例是通过getObject()方法返回实例的,这里传进来是一个匿名内部类,其getObject()方法实现如代码块所示:
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {Object exposedObject = bean;
//判断是否有InstantiationAwareBeanPostProcessors类型的后置处理器
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { //执行类型为SmartInstantiationAwareBeanPostProcessor的后置处理器
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
//返回实例
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}
我们在创建完对象是往三级缓存中存入工厂对象的,以上执行后置处理器的过程返回的对象可能是代理后的对象,这样当我有被其它Bean所引用时,会执行getSingleton()方法,从三级缓存中获取对象并将其添加到二级缓存中,移除三级缓存,这样就能保证被注入的Bean是一个代理后的对象,这是解决循环依赖重要的步骤。
方法3:populateBeanprotected 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;
}
}
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
//标识是否继续属性填充标识
boolean continueWithPropertyPopulation = true;
//如果不是合成的&&有注册InstantiationAwareBeanPostProcessors
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { //遍历执行InstantiationAwareBeanPostProcessors的postProcessAfterInstantiation方法
for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) {InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {continueWithPropertyPopulation = false;
break;
}
}
}
}
//如果经过后置处理器处理后,则跳过后续的步骤
if (!continueWithPropertyPopulation) { return;
}
//获取bean定义信息中的属性值,如 PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
//获取autowire属性值
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
//如果是按name注入或按type注入
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) { //将户配置的属性值封装成MutablePropertyValues
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;
}
//判断是否有注册InstantiationAwareBeanPostProcessors
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 的postProcessProperties方法
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//通过后置处理器后,返回处理后的属性配置信息,如@Autowire注解,会在这步骤进行解析
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);
}
}
autowireByName(beanName, mbd, bw, newPvs),见方法4详解
autowireByType(beanName, mbd, bw, newPvs),见方法7详解
applyPropertyValues(beanName, mbd, bw, pvs),见方法8详解
applyPropertyValues(beanName, mbd, bw, pvs),见方法16详解
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {/过滤掉某些属性类型,返回需要注入的属性名称集
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
//遍历注入
for (String propertyName : propertyNames) { //判断容器中是否存在该属性名称对应的bean
if (containsBean(propertyName)) { //获取实例化Bean
Object bean = getBean(propertyName);
//添加到需要注入的属性值
pvs.add(propertyName, bean);
//注册依赖关系
registerDependentBean(propertyName, beanName);
if (logger.isTraceEnabled()) {logger.trace("Added autowiring by name from bean name '" + beanName +
"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
}
}
else { if (logger.isTraceEnabled()) {logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
"' by name: no matching bean found");
}
}
}
}
unsatisfiedNonSimpleProperties(mbd, bw),见方法5详解
containsBean(propertyName),见方法6详解
protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {Setresult = new TreeSet<>();
//获取当前需要注入的参数值集
PropertyValues pvs = mbd.getPropertyValues();
//获取 bean的属性描述信息
PropertyDescriptor[] pds = bw.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) { //如果有set方法&&不是排除的依赖&&不存在已解析的集合中&&不是简单的属性,如Number、DATE、基本数据类型等
if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) &&
!BeanUtils.isSimpleProperty(pd.getPropertyType())) { result.add(pd.getName());
}
}
return StringUtils.toStringArray(result);
}
方法6:containsBeanpublic boolean containsBean(String name) {//根据别名获取真正的beanName
String beanName = transformedBeanName(name);
//判断三级缓存中是否存在或Bean定义缓存中是否存在该定义
if (containsSingleton(beanName) || containsBeanDefinition(beanName)) { //name不带&符号,并且判断是否是工厂Bean
return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name));
}
// Not found ->check parent.
//查询不到获取父类工厂,并在父工厂中进行查找
BeanFactory parentBeanFactory = getParentBeanFactory();
return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name)));
}
方法7:autowireByTypeprotected void autowireByType(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {//获取类型转换器
TypeConverter converter = getCustomTypeConverter();
if (converter == null) { converter = bw;
}
SetautowiredBeanNames = new LinkedHashSet<>(4);
//过滤掉一些特定的属性类型,返回需要注入的集合
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) { try { //获取属性描述信息
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
// Don't try autowiring by type for type Object: never makes sense,
// even if it technically is a unsatisfied, non-simple property.
//如果不是Object类型则不处理
if (Object.class != pd.getPropertyType()) {//获取该属性的set方法参数信息
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// Do not allow eager init for type matching in case of a prioritized post-processor.
boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
//将set方法信息封装成DependencyDescriptor 对象
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
//解析当前属性所匹配的bean实例,并把解析到的bean实例的beanName存储在autowiredBeanNames中
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
if (autowiredArgument != null) {//添加到需要注入的属性值集合中
pvs.add(propertyName, autowiredArgument);
}
for (String autowiredBeanName : autowiredBeanNames) {//注册依赖关系
registerDependentBean(autowiredBeanName, beanName);
if (logger.isTraceEnabled()) { logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
propertyName + "' to bean named '" + autowiredBeanName + "'");
}
}
autowiredBeanNames.clear();
}
}
catch (BeansException ex) { throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
}
}
}
resolveDependency(desc, beanName, autowiredBeanNames, converter),见方法8详解
方法8:resolveDependencypublic Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
@Nullable SetautowiredBeanNames, @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);
}
//判断依赖类型是否为javaxInjectProviderClass
else if (javaxInjectProviderClass == descriptor.getDependencyType()) { return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
}
else {//获取懒加载代理对象
Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
descriptor, requestingBeanName);
if (result == null) { //解析所需依赖对象
result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
}
return result;
}
}
doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter),见方法9详解
方法9:doResolveDependencypublic Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
@Nullable SetautowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
try {//获取shortcut 对象
Object shortcut = descriptor.resolveShortcut(this);
if (shortcut != null) { return shortcut;
}
//获取依赖类型
Class>type = descriptor.getDependencyType();
//获取指定值,如@qualifier就是在这里解析的
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()));
}
}
//处理类型为多个的情况,如Array、Collection、MAP
Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
if (multipleBeans != null) { return multipleBeans;
}
//从beanFactory中解析候选类,即允许被注入的bean
MapmatchingBeans = findAutowireCandidates(beanName, type, descriptor);
//查询不到时,判断是否有required标识,有则抛异常
if (matchingBeans.isEmpty()) { if (isRequired(descriptor)) {raiseNoMatchingBeanFound(type, descriptor.getResolvableType(), descriptor);
}
return null;
}
String autowiredBeanName;
Object instanceCandidate;
//如果按类型查找出多个bean
if (matchingBeans.size() >1) { //判断是否有primary标志,并返回符合条件的beanName
autowiredBeanName = determineAutowireCandidate(matchingBeans, descriptor);
if (autowiredBeanName == null) {//有require标识,或者不是Collection等容器类型,则抛异常
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;
}
}
//获取符合条件的实例
instanceCandidate = matchingBeans.get(autowiredBeanName);
}
else { // We have exactly one match.
//只有一个的情况下则直接获取第一个值
Map.Entryentry = matchingBeans.entrySet().iterator().next();
autowiredBeanName = entry.getKey();
instanceCandidate = entry.getValue();
}
//添加autowiredBeanName到autowiredBeanNames中
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);
}
}
findAutowireCandidates(beanName, type, descriptor),见方法10详解
determineAutowireCandidate(matchingBeans, descriptor),见方法13详解
protected MapfindAutowireCandidates(
@Nullable String beanName, Class>requiredType, DependencyDescriptor descriptor) {//从beanFactory工厂中通过类型获取对应的beanName
String[] candidateNames = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
this, requiredType, true, descriptor.isEager());
Mapresult = new LinkedHashMap<>(candidateNames.length);
//遍历依赖缓存
for (Map.Entry, Object>classObjectEntry : this.resolvableDependencies.entrySet()) { //获取key值
Class>autowiringType = classObjectEntry.getKey();
//判断类型是否所需类型
if (autowiringType.isAssignableFrom(requiredType)) { //获取依赖value
Object autowiringValue = classObjectEntry.getValue();
//判断需要的类型跟当前获取的值autowiringValue 不是同个类型
//并且如果autowiringValue是工厂对象的话,则调用getObject方法获取
autowiringValue = AutowireUtils.resolveAutowiringValue(autowiringValue, requiredType);
//如果两个类型一致,则生成一个新的beanName,并放入map中
if (requiredType.isInstance(autowiringValue)) {result.put(ObjectUtils.identityToString(autowiringValue), autowiringValue);
break;
}
}
}
//遍历候选类集合
for (String candidate : candidateNames) { //依赖所需对象不能是当前bean本身,如B中有属性B这种情况&&判断允许被其它bean注入
if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, descriptor)) { addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
//如果前面获取不到合适的类型
if (result.isEmpty()) { //判断是否是容器类型,如Collection
boolean multiple = indicatesMultipleBeans(requiredType);
// Consider fallback matches if the first pass failed to find anything...
DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch();
//使用备用的依赖描述器再去获取一遍符合注入属性类型的beanName
for (String candidate : candidateNames) { if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor) &&
(!multiple || getAutowireCandidateResolver().hasQualifier(descriptor))) {addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
//还是没有符合注入属性类型的beanName,又不是集合类型,考虑自引用,符合条件则将候选者添加到result中
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.
for (String candidate : candidateNames) {if (isSelfReference(beanName, candidate) &&
(!(descriptor instanceof MultiElementDescriptor) || !beanName.equals(candidate)) &&
isAutowireCandidate(candidate, fallbackDescriptor)) {addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
}
}
return result;
}
addCandidateEntry(result, candidate, descriptor, requiredType),见方法11详解
方法11:addCandidateEntryprivate void addCandidateEntry(Mapcandidates, String candidateName,
DependencyDescriptor descriptor, Class>requiredType) {//如果是一个MultiElementDescriptor类型的
if (descriptor instanceof MultiElementDescriptor) { //实例化
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 { //将candidateName跟candidateName的class对象存入缓存中
candidates.put(candidateName, getType(candidateName));
}
}
getType(candidateName),见方法12详解
方法12:getTypepublic Class>getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException {String beanName = transformedBeanName(name);
// Check manually registered singletons.
//从一级缓存中获取对象
Object beanInstance = getSingleton(beanName, false);
if (beanInstance != null && beanInstance.getClass() != NullBean.class) { //如果是FactoryBean ,则调用其getObjectType返回真正的实例class
if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) { return getTypeForFactoryBean((FactoryBean>) beanInstance);
}
else { //返回class对象
return beanInstance.getClass();
}
}
// No singleton instance found ->check bean definition.
//前面如果查询不到,则获取父工厂进行查询
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // No bean definition found in this factory ->delegate to parent.
return parentBeanFactory.getType(originalBeanName(name));
}
//获取合并的Bean定义信息
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// Check decorated bean definition, if any: We assume it'll be easier
// to determine the decorated bean's type than the proxy's type.
//获取目标代理对象
BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
//判断name是否带有&前缀,如果不是工厂对象
if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) { RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
//获取beanName对应的class对象
Class>targetClass = predictBeanType(dbd.getBeanName(), tbd);
if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) { return targetClass;
}
}
//获取beanName对应的class对象
Class>beanClass = predictBeanType(beanName, mbd);
// Check bean class whether we're dealing with a FactoryBean.
//如果不为空&&类型为FactoryBean
if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) { //name不带&符号,即不是获取工厂对象本身
if (!BeanFactoryUtils.isFactoryDereference(name)) { // If it's a FactoryBean, we want to look at what it creates, not at the factory class.
//返回实际的对象class
return getTypeForFactoryBean(beanName, mbd, allowFactoryBeanInit).resolve();
}
else { return beanClass;
}
}
else { return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null);
}
}
方法13:determineAutowireCandidateprotected String determineAutowireCandidate(Mapcandidates, DependencyDescriptor descriptor) {//获取需要注入依赖的类型
Class>requiredType = descriptor.getDependencyType();
//解析,筛选带有primary属性的beanName
String primaryCandidate = determinePrimaryCandidate(candidates, requiredType);
if (primaryCandidate != null) { return primaryCandidate;
}
//如果被注入类有实现OrderComparator接口,则进行比较筛选出Priority,值越低优先级越高
String priorityCandidate = determineHighestPriorityCandidate(candidates, requiredType);
if (priorityCandidate != null) { return priorityCandidate;
}
// Fallback
//遍历候选bean
for (Map.Entryentry : 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;
}
determinePrimaryCandidate(candidates, requiredType),见方法14详解
determineHighestPriorityCandidate(candidates, requiredType),见方法15详解
方法14:determinePrimaryCandidateprotected String determinePrimaryCandidate(Mapcandidates, Class>requiredType) {String primaryBeanName = null;
for (Map.Entryentry : candidates.entrySet()) { String candidateBeanName = entry.getKey();
Object beanInstance = entry.getValue();
//判断是否有Primary标识
if (isPrimary(candidateBeanName, beanInstance)) { if (primaryBeanName != null) {boolean candidateLocal = containsBeanDefinition(candidateBeanName);
boolean primaryLocal = containsBeanDefinition(primaryBeanName);
//如果存在两个依赖都有其Primary,则抛异常
if (candidateLocal && primaryLocal) {throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(),
"more than one 'primary' bean found among candidates: " + candidates.keySet());
}
else if (candidateLocal) {//赋值
primaryBeanName = candidateBeanName;
}
}
else {//赋值
primaryBeanName = candidateBeanName;
}
}
}
return primaryBeanName;
}
方法15:determineHighestPriorityCandidateprotected String determineHighestPriorityCandidate(Mapcandidates, Class>requiredType) {//最高优先级的beanName
String highestPriorityBeanName = null;
//最高优先级值
Integer highestPriority = null;
//遍历
for (Map.Entryentry : candidates.entrySet()) { String candidateBeanName = entry.getKey();
Object beanInstance = entry.getValue();
if (beanInstance != null) { //获取优先级
Integer candidatePriority = getPriority(beanInstance);
if (candidatePriority != null) {if (highestPriorityBeanName != null) {//存在两个优先级一样则抛异常
if (candidatePriority.equals(highestPriority)) { throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(),
"Multiple beans found with the same priority ('" + highestPriority +
"') among candidates: " + candidates.keySet());
}
//比较,candidatePriority 值越低则优先级越高
else if (candidatePriority< highestPriority) { highestPriorityBeanName = candidateBeanName;
highestPriority = candidatePriority;
}
}
else {//第一次则直接赋值
highestPriorityBeanName = candidateBeanName;
highestPriority = candidatePriority;
}
}
}
}
return highestPriorityBeanName;
}
方法16:applyPropertyValuesprotected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {、
//判断注入参数是否为空
if (pvs.isEmpty()) { return;
}
if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) { ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
}
MutablePropertyValues mpvs = null;
//存在原始参数值
Listoriginal;
//如果参数MutablePropertyValues类型
if (pvs instanceof MutablePropertyValues) { mpvs = (MutablePropertyValues) pvs;
//如果已经转换过,则直接设置值
if (mpvs.isConverted()) { // Shortcut: use the pre-converted values as-is.
try {bw.setPropertyValues(mpvs);
return;
}
catch (BeansException ex) {throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
original = mpvs.getPropertyValueList();
}
else { original = Arrays.asList(pvs.getPropertyValues());
}
//获取类型转换器
TypeConverter converter = getCustomTypeConverter();
if (converter == null) { converter = bw;
}
//创建解析器
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
// Create a deep copy, resolving any references for values.
//存放拷贝参数值,即通知转换后的值
ListdeepCopy = new ArrayList<>(original.size());
boolean resolveNecessary = false;
for (PropertyValue pv : original) { //如果已经转换过,则加入到深拷贝集合中
if (pv.isConverted()) { deepCopy.add(pv);
}
else { //获取参数名称
String propertyName = pv.getName();
//获取参数值
Object originalValue = pv.getValue();
//判断值是否是AutowiredPropertyMarker类型
if (originalValue == AutowiredPropertyMarker.INSTANCE) {//获取set方法
Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
if (writeMethod == null) {throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
}
//将参数值封装成DependencyDescriptor
originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
}
//对值进行解析转换,如果类型是beanFactory工厂中的beanDefinition封装的信息时,则会进行实例化
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
//转换后的值
Object convertedValue = resolvedValue;
//判断是否有写权限&&没有嵌套属性,如不包含“.”或者“[”符号
boolean convertible = bw.isWritableProperty(propertyName) &&
!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
if (convertible) {//类型转换
convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
}
// Possibly store converted value in merged bean definition,
// in order to avoid re-conversion for every created bean instance.
//如果解析值跟转换后的值一直
if (resolvedValue == originalValue) {//转换标志
if (convertible) {//设置转换后的值
pv.setConvertedValue(convertedValue);
}
//加入解析后的集合中
deepCopy.add(pv);
}
else if (convertible && originalValue instanceof TypedStringValue &&
!((TypedStringValue) originalValue).isDynamic() &&
!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {pv.setConvertedValue(convertedValue);
deepCopy.add(pv);
}
else {resolveNecessary = true;
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
}
if (mpvs != null && !resolveNecessary) { mpvs.setConverted();
}
// Set our (possibly massaged) deep copy.
try { //属性值注入
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
catch (BeansException ex) { throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
valueResolver.resolveValueIfNecessary(pv, originalValue),见方法17详解
方法17:resolveValueIfNecessarypublic Object resolveValueIfNecessary(Object argName, @Nullable Object value) {// We must check each value to see whether it requires a runtime reference
// to another bean to be resolved.
if (value instanceof RuntimeBeanReference) { //如果参数值为RuntimeBeanReference类型,则调用getBean方法获取创建实例
RuntimeBeanReference ref = (RuntimeBeanReference) value;
return resolveReference(argName, ref);
}
else if (value instanceof RuntimeBeanNameReference) { //获取依赖的beanName
String refName = ((RuntimeBeanNameReference) value).getBeanName();
refName = String.valueOf(doEvaluate(refName));
if (!this.beanFactory.containsBean(refName)) { throw new BeanDefinitionStoreException(
"Invalid bean name '" + refName + "' in bean reference for " + argName);
}
return refName;
}
else if (value instanceof BeanDefinitionHolder) { // Resolve BeanDefinitionHolder: contains BeanDefinition with name and aliases.
//解析BeanDefinitionHolder:包含带有名称和别名的BeanDefinition。
BeanDefinitionHolder bdHolder = (BeanDefinitionHolder) value;
return resolveInnerBean(argName, bdHolder.getBeanName(), bdHolder.getBeanDefinition());
}
else if (value instanceof BeanDefinition) { // Resolve plain BeanDefinition, without contained name: use dummy name.
//解析普通的BeanDefinition,不包含名称:使用虚拟名称
BeanDefinition bd = (BeanDefinition) value;
String innerBeanName = "(inner bean)" + BeanFactoryUtils.GENERATED_BEAN_NAME_SEPARATOR +
ObjectUtils.getIdentityHexString(bd);
return resolveInnerBean(argName, innerBeanName, bd);
}
else if (value instanceof DependencyDescriptor) { SetautowiredBeanNames = new LinkedHashSet<>(4);
//创建实例,并解析出候选的bean信息
Object result = this.beanFactory.resolveDependency(
(DependencyDescriptor) value, this.beanName, autowiredBeanNames, this.typeConverter);
//实例化,并注册依赖关系
for (String autowiredBeanName : autowiredBeanNames) { if (this.beanFactory.containsBean(autowiredBeanName)) {this.beanFactory.registerDependentBean(autowiredBeanName, this.beanName);
}
}
return result;
}
else if (value instanceof ManagedArray) { // May need to resolve contained runtime references.
ManagedArray array = (ManagedArray) value;
Class>elementType = array.resolvedElementType;
if (elementType == null) { String elementTypeName = array.getElementTypeName();
if (StringUtils.hasText(elementTypeName)) {try {elementType = ClassUtils.forName(elementTypeName, this.beanFactory.getBeanClassLoader());
array.resolvedElementType = elementType;
}
catch (Throwable ex) {// Improve the message by showing the context.
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Error resolving array type for " + argName, ex);
}
}
else {elementType = Object.class;
}
}
return resolveManagedArray(argName, (List>) value, elementType);
}
else if (value instanceof ManagedList) { // May need to resolve contained runtime references.
return resolveManagedList(argName, (List>) value);
}
else if (value instanceof ManagedSet) { // May need to resolve contained runtime references.
return resolveManagedSet(argName, (Set>) value);
}
else if (value instanceof ManagedMap) { // May need to resolve contained runtime references.
return resolveManagedMap(argName, (Map, ?>) value);
}
else if (value instanceof ManagedProperties) { Properties original = (Properties) value;
Properties copy = new Properties();
original.forEach((propKey, propValue) ->{ if (propKey instanceof TypedStringValue) {propKey = evaluate((TypedStringValue) propKey);
}
if (propValue instanceof TypedStringValue) {propValue = evaluate((TypedStringValue) propValue);
}
if (propKey == null || propValue == null) {throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Error converting Properties key/value pair for " + argName + ": resolved to null");
}
copy.put(propKey, propValue);
});
return copy;
}
//如果是字符串
else if (value instanceof TypedStringValue) { // Convert value to target type here.
//进行类型解析
TypedStringValue typedStringValue = (TypedStringValue) value;
Object valueObject = evaluate(typedStringValue);
try { //获取目标类型
Class>resolvedTargetType = resolveTargetType(typedStringValue);
if (resolvedTargetType != null) {return this.typeConverter.convertIfNecessary(valueObject, resolvedTargetType);
}
else {return valueObject;
}
}
catch (Throwable ex) { // Improve the message by showing the context.
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Error converting typed String value for " + argName, ex);
}
}
else if (value instanceof NullBean) { return null;
}
else { return evaluate(value);
}
}
限于篇幅,本篇文章讲解到这,后续文章继续讲解populateBean及其createBean后续流程。
总结本篇文章讲解了属性注入过程中所需参数的解析工作,一般我们可以在xml配置文件中指定其参数值,或通知设置autowire属性指定byType或byName,从beanFactory查找出所需注入对象,梳理一下流程。
1、获取BeanDefinition中已经解析的参数信息
2、判断是否有autowire属性,如果其指定值为byName,则通过其属性名称去缓存中获取实例,并封装到参数集合中。
3、如果autowire属性值为byType,则尝试通过需要注入的beanName从依赖缓存resolvableDependencies中获取,及从beanFactory工厂中获取类型为注入Bean类型的定义信息,返回beanName:class集合
4、如果候选的依赖有多个值,则遍历查询是否有primary属性,有则筛选对应的bean。如果都没有primary属性,则判断是否有实现OrderComparator接口,则进行比较筛选出Priority,值越低优先级越高。前面两者都不满足时,判断是否有候选的beanName值与要注入的属性的依赖名称一致,有则返回。没有筛选出则抛出异常
5、对筛选出来的候选类进行实例化,并封装到属性参数中
6、对所有的参数类型进行转换创建,如参数类型RuntimeBeanReference时,会调用getBean进行获取创建,最后通过反射的返回注入到Bean中。
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧