在spring初始化 bean的时候

代码片段1,bean当前的一些定义信息,如果没被处理过,则调用处理器修改

     AbstractAutowireCapableBeanFactory

         //修改bean的一些定义信息
		synchronized (mbd.postProcessingLock) {
			if (!mbd.postProcessed) {//mbd是当前初始化bean的一些定义的信息
				applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
				mbd.postProcessed = true;
			}
		}

代码片段2,执行,对应的处理器方法

AbstractAutowireCapableBeanFactory

protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName)
			throws BeansException {

		try {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof MergedBeanDefinitionPostProcessor) {
					MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
                       //执行bean的修改定义信息的方法
					bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
				}
			}
		}
		catch (Exception ex) {
			throw new BeanCreationException(mbd.getResourceDe ion(), beanName,
					\"Post-processing failed of bean type [\" + beanType + \"] failed\", ex);
		}
	}

代码片段3,查找构建元数据,

AutowiredAnnotationBeanPostProcessor

	@Override
	public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
		if (beanType != null) {
            //查找自动注入的注解的元信息
			Injection data  data = findAutowiring data(beanName, beanType, null);
			 data.checkConfigMembers(beanDefinition);
		}
	}


/////////////////////////////////////////
private Injection data findAutowiring data(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.
           //查找缓存是否有信息,有就返回
		Injection data  data = this.injection dataCache.get(cacheKey);
		if (Injection data.needsRefresh( data, clazz)) {
			synchronized (this.injection dataCache) {
				 data = this.injection dataCache.get(cacheKey);
				if (Injection data.needsRefresh( data, clazz)) {
					if ( data != null) {
						 data.clear(pvs);
					}
					try {//如果没有就构建这个类的 相关注解的信息
						 data = buildAutowiring data(clazz);
						this.injection dataCache.put(cacheKey,  data);
					}
					catch (NoClassDefFoundError err) {
						throw new IllegalStateException(\"Failed to introspect bean class [\" + clazz.getName() +
								\"] for autowiring  data: could not find class that it depends on\", err);
					}
				}
			}
		}
		return  data;
	}

//////////////////////////////////////////////////
private Injection data buildAutowiring data(final Class<?> clazz) {
		 edList<Injection data.InjectedElement> elements = new  edList<Injection data.InjectedElement>();
		Class<?> targetClass = clazz;

		do {
            //记录的是当前有@autowired注解信息 或者@value的属性(需要自动注入值的)
			final  edList<Injection data.InjectedElement> currElements =
					new  edList<Injection data.InjectedElement>();
            //反射获取相关的字段信息,并且回调dowith方法
			ReflectionUtils.doWithLocalFields(targetClass, new ReflectionUtils.FieldCallback() {
				@Override
                //field是遍历到的字段
				public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                    //查找注解信息,这个是在这个类构造方法的时候放入缓存的
                     //ann 是返回的这个属性的注解信息
					AnnotationAttributes ann = findAutowiredAnnotation(field);
					if (ann != null) {
						if (Modifier.isStatic(field.getModifiers())) {//静态属性不行
							if (logger.isWarnEnabled()) {
								logger.warn(\"Autowired annotation is not supported on static fields: \" + field);
							}
							return;
						}
						boolean required = determineRequiredStatus(ann);
						currElements.add(new AutowiredFieldElement(field, required));
					}
				}
			});
            
            //上面是查找自动,这个是查找方法的 没啥说的
			ReflectionUtils.doWithLocalMethods(targetClass, new ReflectionUtils.MethodCallback() {
				@Override
				public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
					Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
					if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
						return;
					}
					AnnotationAttributes ann = findAutowiredAnnotation(bridgedMethod);
					if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
						if (Modifier.isStatic(method.getModifiers())) {
							if (logger.isWarnEnabled()) {
								logger.warn(\"Autowired annotation is not supported on static methods: \" + method);
							}
							return;
						}
						if (method.getParameterTypes().length == 0) {
							if (logger.isWarnEnabled()) {
								logger.warn(\"Autowired annotation should be used on methods with parameters: \" + method);
							}
						}
						boolean required = determineRequiredStatus(ann);
						PropertyDe or pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
						currElements.add(new AutowiredMethodElement(method, required, pd));
					}
				}
			});

			elements.addAll(0, currElements);
    //进行循环查找父类的这些注解,并且加入,并且父类的信息放到集合前面,优先赋值
			targetClass = targetClass.getSuperclass();
		}
		while (targetClass != null && targetClass !=  .class);

		return new Injection data(clazz, elements);//返回的就是被注解修饰
	}
//////////////////////////////////////////////////////////
private AnnotationAttributes findAutowiredAnnotation(Accessible  ao) {
		if (ao.getAnnotations().length > 0) {//autowiredAnnotationTypes就是@autowired,@value,@inject
			for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
				AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(ao, type);
				if (attributes != null) {
					return attributes;
				}
			}
		}
		return null;
	}

///////////////////////////////////////////////////////
AnnotatedElementUtils


private static <T> T searchWithGetSemantics(AnnotatedElement element,
			Class<? extends Annotation> annotationType, String annotationName,
			Processor<T> processor, Set<AnnotatedElement> visited, int  Depth) {

		Assert.notNull(element, \"AnnotatedElement must not be null\");

		if (visited.add(element)) {//当前属性只解析一次
			try {
				// Start searching within locally declared annotations
				List<Annotation> declaredAnnotations = Arrays.asList(element.getDeclaredAnnotations());
                   //result为返回的当前注解的信息,包括注解里面设置的各种值。
				T result = searchWithGetSemanticsInAnnotations(element, declaredAnnotations,
						annotationType, annotationName, processor, visited,  Depth);
				if (result != null) {
					return result;
				}

				if (element instanceof Class) {  //  otherwise getAnnotations doesn\'t return anything new
					List<Annotation> inheritedAnnotations = new ArrayList<Annotation>();
					for (Annotation annotation : element.getAnnotations()) {
						if (!declaredAnnotations.contains(annotation)) {
							inheritedAnnotations.add(annotation);
						}
					}

					// Continue searching within inherited annotations
					result = searchWithGetSemanticsInAnnotations(element, inheritedAnnotations,
							annotationType, annotationName, processor, visited,  Depth);
					if (result != null) {
						return result;
					}
				}
			}
			catch (Exception ex) {
				AnnotationUtils.handleIntrospectionFailure(element, ex);
			}
		}

		return null;
	}

查找到注解修饰的方法和字段了,是该赋值了

 

AbstractAutowireCapableBeanFactory

protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
		PropertyValues pvs = mbd.getPropertyValues();

		if (bw == null) {
			if (!pvs.isEmpty()) {
				throw new BeanCreationException(
						mbd.getResourceDe ion(), 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;

		if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
						continueWithPropertyPopulation = false;
						break;
					}
				}
			}
		}

		if (!continueWithPropertyPopulation) {
			return;
		}

		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
				mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
			MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

			// Add property values  d on autowire by name if applicable.
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
				autowireByName(beanName, mbd, bw, newPvs);
			}

			// Add property values  d on autowire by type if applicable.
			if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
				autowireByType(beanName, mbd, bw, newPvs);
			}

			pvs = newPvs;
		}

		boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
		boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

		if (hasInstAwareBpps || needsDepCheck) {
			PropertyDe or[] filteredPds = filterPropertyDe orsForDependencyCheck(bw, mbd.allowCaching);
			if (hasInstAwareBpps) {
				for (BeanPostProcessor bp : getBeanPostProcessors()) {
					if (bp instanceof InstantiationAwareBeanPostProcessor) {
                        //又是postProcessors
						InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                         //开始赋值
						pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
						if (pvs == null) {
							return;
						}
					}
				}
			}
			if (needsDepCheck) {
				checkDependencies(beanName, mbd, filteredPds, pvs);
			}
		}

		applyPropertyValues(beanName, mbd, bw, pvs);
	}
///////////////////////////////////////////////////
AutowiredAnnotationBeanPostProcessor

@Override
	public PropertyValues postProcessPropertyValues(
			PropertyValues pvs, PropertyDe or[] pds,   bean, String beanName) throws BeansException {
    //查找 查找到刚刚需要被注入的元信息
		Injection data  data = findAutowiring data(beanName, bean.getClass(), pvs);
		try {
            //注入操作
			 data.inject(bean, beanName, pvs);
		}
		catch (Throwable ex) {
			throw new BeanCreationException(beanName, \"Injection of autowired dependencies failed\", ex);
		}
		return pvs;
	}
///////////////////////////////////////////////////////
Injection data
public void inject(  target, String beanName, PropertyValues pvs) throws Throwable {
		Collection<InjectedElement> elementsToIterate =
				(this.checkedElements != null ? this.checkedElements : this.injectedElements);
		if (!elementsToIterate.isEmpty()) {
			boolean debug = logger.isDebugEnabled();
			for (InjectedElement element : elementsToIterate) {
				if (debug) {
					logger.debug(\"Processing injected element of bean \'\" + beanName + \"\': \" + element);
				}
                 //InjectedElement 有两个实现类AutowiredMethodElement,AutowiredFieldElement
				element.inject(target, beanName, pvs);
			}
		}
	}
//////////////////////////////////////////////////

//看下属性赋值的流程

	@Override
		protected void inject(  bean, String beanName, PropertyValues pvs) throws Throwable {
			Field field = (Field) this.member;
			try {
				  value;
				if (this.cached) {
					value = resolvedCachedArgument(beanName, this.cachedFieldValue);
				}
				else {
                    //字段相关的信息包装类
					DependencyDe or desc = new DependencyDe or(field, this.required);
					desc.setContainingClass(bean.getClass());
					Set<String> autowiredBeanNames = new  edHashSet<String>(1);
					TypeConverter typeConverter = beanFactory.getTypeConverter();
                      //解析需要注入的值,根据信息包装类的信息,从容器中查找合适对象
					value = beanFactory.resolveDependency(desc, beanName, autowiredBeanNames, typeConverter);
					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)) {
										if (beanFactory.isTypeMatch(autowiredBeanName, field.getType())) {
											this.cachedFieldValue = new RuntimeBeanReference(autowiredBeanName);
										}
									}
								}
							}
							else {
								this.cachedFieldValue = null;
							}
							this.cached = true;
						}
					}
				}
				if (value != null) {//设值注入
					ReflectionUtils.makeAccessible(field);
					field.set(bean, value);
				}
			}
			catch (Throwable ex) {
				throw new BeanCreationException(\"Could not autowire field: \" + field, ex);
			}
		}
	}
/////////////////////////////////
DefaultListableBeanFactory
	@Override
	public   resolveDependency(DependencyDe or de or, String beanName,
			Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {

		de or.initParameterNameDiscovery(getParameterNameDiscoverer());
		if (de or.getDependencyType().equals(javaUtilOptionalClass)) {
			return new OptionalDependencyFactory().createOptionalDependency(de or, beanName);
		}
		else if ( Factory.class == de or.getDependencyType()) {
			return new Dependency Factory(de or, beanName);
		}
		else if (javaxInjectProviderClass == de or.getDependencyType()) {
			return new DependencyProviderFactory().createDependencyProvider(de or, beanName);
		}
		else {
               //如果没使用懒加载,result为null,进行解析,如果使用了lazy,则会初始化该lazy对象
			  result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(de or, beanName);
			if (result == null) {
				result = doResolveDependency(de or, beanName, autowiredBeanNames, typeConverter);
			}
			return result;
		}
	}
////////////////////////////////////////////
决定需要被注入的值
public   doResolveDependency(DependencyDe or de or, String beanName,
			Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {

		Class<?> type = de or.getDependencyType();
        //@Value注解解析
		  value = getAutowireCandidateResolver().getSuggestedValue(de or);
		if (value != null) {
			if (value instanceof String) {
                //获取spring表达式取
				String strVal = resolve dedValue((String) value);
				BeanDefinition bd = (beanName != null && containsBean(beanName) ? getMergedBeanDefinition(beanName) : null);
                   //计算给属性的值
				value = evaluateBeanDefinitionString(strVal, bd);
			}
			TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
			return (de or.getField() != null ?
					converter.convertIfNecessary(value, type, de or.getField()) :
					converter.convertIfNecessary(value, type, de or.getMethodParameter()));
		}
        //如果设值的属性是list
		if (type.isArray()) {
			Class<?> componentType = type.getComponentType();
			DependencyDe or targetDesc = new DependencyDe or(de or);
			targetDesc.increaseNestingLevel();
             //查找到所有和目标类型匹配的组件对象,key是beanname,value即对象
			Map<String,  > matchingBeans = findAutowireCandidates(beanName, componentType, targetDesc);
			if (matchingBeans.isEmpty()) {
				if (de or.isRequired()) {
					raiseNoSuchBeanDefinitionException(componentType, \"array of \" + componentType.getName(), de or);
				}
				return null;
			}
			if (autowiredBeanNames != null) {
				autowiredBeanNames.addAll(matchingBeans.keySet());
			}
			TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
			  result = converter.convertIfNecessary(matchingBeans.values(), type);
			if (getDependencyComparator() != null && result instanceof  []) {
				Arrays.sort(( []) result, adaptDependencyComparator(matchingBeans));
			}
			return result;
		}
		else if (Collection.class.isAssignableFrom(type) && type.isInterface()) {
			Class<?> elementType = de or.getCollectionType();
			if (elementType == null) {
				if (de or.isRequired()) {
					throw new FatalBeanException(\"No element type declared for collection [\" + type.getName() + \"]\");
				}
				return null;
			}
			DependencyDe or targetDesc = new DependencyDe or(de or);
			targetDesc.increaseNestingLevel();
			Map<String,  > matchingBeans = findAutowireCandidates(beanName, elementType, targetDesc);
			if (matchingBeans.isEmpty()) {
				if (de or.isRequired()) {
					raiseNoSuchBeanDefinitionException(elementType, \"collection of \" + elementType.getName(), de or);
				}
				return null;
			}
			if (autowiredBeanNames != null) {
				autowiredBeanNames.addAll(matchingBeans.keySet());
			}
			TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
			  result = converter.convertIfNecessary(matchingBeans.values(), type);
			if (getDependencyComparator() != null && result instanceof List) {
				Collections.sort((List<?>) result, adaptDependencyComparator(matchingBeans));
			}
			return result;
		}//Map的组件查找
		else if (Map.class.isAssignableFrom(type) && type.isInterface()) {
			Class<?> keyType = de or.getMapKeyType();
              //Map的key只能定义string,如果要注入值
			if (String.class != keyType) {
				if (de or.isRequired()) {
					throw new FatalBeanException(\"Key type [\" + keyType + \"] of map [\" + type.getName() +
							\"] must be [java.lang.String]\");
				}
				return null;
			}
              //获取value的类型
			Class<?> valueType = de or.getMapValueType();
			if (valueType == null) {
				if (de or.isRequired()) {
					throw new FatalBeanException(\"No value type declared for map [\" + type.getName() + \"]\");
				}
				return null;
			}
			DependencyDe or targetDesc = new DependencyDe or(de or);
			targetDesc.increaseNestingLevel();
			Map<String,  > matchingBeans = findAutowireCandidates(beanName, valueType, targetDesc);
			if (matchingBeans.isEmpty()) {
				if (de or.isRequired()) {
					raiseNoSuchBeanDefinitionException(valueType, \"map with value type \" + valueType.getName(), de or);
				}
				return null;
			}
			if (autowiredBeanNames != null) {
				autowiredBeanNames.addAll(matchingBeans.keySet());
			}
			return matchingBeans;
		}
		else {//普通对象的
			Map<String,  > matchingBeans = findAutowireCandidates(beanName, type, de or);
			if (matchingBeans.isEmpty()) {
				if (de or.isRequired()) {
					raiseNoSuchBeanDefinitionException(type, \"\", de or);
				}
				return null;
			}
			if (matchingBeans.size() > 1) {//如果查找到的结果大于1
				String primaryBeanName = determineAutowireCandidate(matchingBeans, de or);
				if (primaryBeanName == null) {
					throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet());
				}
				if (autowiredBeanNames != null) {
					autowiredBeanNames.add(primaryBeanName);
				}
				return matchingBeans.get(primaryBeanName);
			}
			// We have exactly one match.
			Map.Entry<String,  > entry = matchingBeans.entrySet().iterator().next();
			if (autowiredBeanNames != null) {
				autowiredBeanNames.add(entry.getKey());
			}
			return entry.getValue();
		}
	}

///////////////////////////////////////
protected String determineAutowireCandidate(Map<String,  > candidateBeans, DependencyDe or de or) {
		Class<?> requiredType = de or.getDependencyType();
        //被@primary修饰的优先
		String primaryCandidate = determinePrimaryCandidate(candidateBeans, requiredType);
		if (primaryCandidate != null) {
			return primaryCandidate;
		}
        //@Order修饰的则根据优先顺序
		String priorityCandidate = determineHighestPriorityCandidate(candidateBeans, requiredType);
		if (priorityCandidate != null) {
			return priorityCandidate;
		}
		// Fallback
		for (Map.Entry<String,  > entry : candidateBeans.entrySet()) {
			String candidateBeanName = entry.getKey();
			  beanInstance = entry.getValue();
            //根据属性名称匹配
			if ((beanInstance != null && this.resolvableDependencies.containsValue(beanInstance)) ||
					matchesBeanName(candidateBeanName, de or.getDependencyName())) {
				return candidateBeanName;
			}
		}
		return null;
	}

 

 

 

收藏 打印