봄 5.x를 소스 여행 스물셋의 getBean 자세한 생성자 나인 인스턴스화

봄 5.x를 소스 여행 스물셋 자세한의 getBean 찾고 생성자 나인

determineConstructorsFromBeanPostProcessors

인스턴스화 공정 설비 앞에 말하면, 이제 제 1 프로세서, 적절한 방법을 식별하도록 구성되며, 통상의 생성자 인스턴스화 말할 수있다 :

@Nullable
	protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
			throws BeansException {

		if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
					SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
					Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
					if (ctors != null) {
						return ctors;
					}
				}
			}
		}
		return null;
	}

AutowiredAnnotationBeanPostProcessor 的 determineCandidateConstructors

메인 프로세서는 검사 시작 행해진 Lookup이어서, 노트에 따르면 추가의 처리 방법. 주로 생성자 인수 뒤, 먼저 캐시를 획득하고, 당신은 모든 생성자를 얻을 경우 비어있는 경우, 다음 판단 네, 다음 부모를 얻을, 프록시 클래스 아니라, 각 생성자는 메모를 얻기 위해 통과해야 클래스의 우리 자신의 정의입니다 클래스는 다시 메모를 얻을. 주석이 존재하는 경우, 볼 이 다수있는 경우, 재산 또는 1이고 , 다른 IS는 모든 경우에 그가 무엇으로 알 수 없기 때문에 오류가있을 것입니다 가능하다. 오직 하나의 경우 , 경고가보고됩니다. 당신이있는 경우 의견을, 당신이 우선 순위를 주석, 그렇지 않은 경우에만 생성자의 매개 변수와 우선 순위가 생성자, 다음으로 우선 순위 생성자가 관련되므로 기본적으로하지 우선 순위는 다음, 나머지는 기본 생성자입니다 가. 기본 생성자를 찾을 수 인스턴스화하지만, 찾을 수 없습니다 때 여러 생성자가있는 경우 주 그가 사용할지 모르는 사실 매개 변수는 예외가보고됩니다있다.AutowiredrequiredtruetruefalsefalsefalseAutowiredKotlin

@Override
	@Nullable
	public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
			throws BeanCreationException {

		// 查找lookup
		if (!this.lookupMethodsChecked.contains(beanName)) {
			if (AnnotationUtils.isCandidateClass(beanClass, Lookup.class)) {
				try {
					Class<?> targetClass = beanClass;
					do {//遍历当前类以及所有父类,找出Lookup注解的方法进行处理
						ReflectionUtils.doWithLocalMethods(targetClass, method -> {
							Lookup lookup = method.getAnnotation(Lookup.class);
							if (lookup != null) {
								Assert.state(this.beanFactory != null, "No BeanFactory available");
								LookupOverride override = new LookupOverride(method, lookup.value());
								try {
									RootBeanDefinition mbd = (RootBeanDefinition)
											this.beanFactory.getMergedBeanDefinition(beanName);
									mbd.getMethodOverrides().addOverride(override);
								}
								catch (NoSuchBeanDefinitionException ex) {
									throw new BeanCreationException(beanName,
											"Cannot apply @Lookup to beans without corresponding bean definition");
								}
							}
						});
						targetClass = targetClass.getSuperclass();
					}
					while (targetClass != null && targetClass != Object.class);//遍历父类,直到Object

				}
				catch (IllegalStateException ex) {
					throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
				}
			}
			this.lookupMethodsChecked.add(beanName);//已经检查过
		}

		//先检查一遍缓存
		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 {
						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);
					}
					List<Constructor<?>> candidates = new ArrayList<>(rawCandidates.length);
					Constructor<?> requiredConstructor = null;//需要的构造方法
					Constructor<?> defaultConstructor = null;//默认构造方法
					Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);//优先的构造方法,Kotlin的类才有,一般都是空
					int nonSyntheticConstructors = 0;
					for (Constructor<?> candidate : rawCandidates) {
						if (!candidate.isSynthetic()) {//非合成的方法
							nonSyntheticConstructors++;
						}
						else if (primaryConstructor != null) {
							continue;
						}
						MergedAnnotation<?> ann = findAutowiredAnnotation(candidate);//寻找Autowired和value的注解
						if (ann == null) {
							Class<?> userClass = ClassUtils.getUserClass(beanClass);
							if (userClass != beanClass) {//如果是有代理的,找到被代理类
								try {
									Constructor<?> superCtor =//获取构造方法
											userClass.getDeclaredConstructor(candidate.getParameterTypes());
									ann = findAutowiredAnnotation(superCtor);//继续寻找Autowired和value的注解
								}
								catch (NoSuchMethodException ex) {
									// Simply proceed, no equivalent superclass constructor found...
								}
							}
						}
						if (ann != null) {
							if (requiredConstructor != null) {//有两个Autowired注解,冲突了
								throw new BeanCreationException(beanName,
										"Invalid autowire-marked constructor: " + candidate +
										". Found constructor with 'required' Autowired annotation already: " +
										requiredConstructor);
							}
							boolean required = determineRequiredStatus(ann);//是否需要,默认是true
							if (required) {
								if (!candidates.isEmpty()) {//如果已经有required=false了,又来了一个required=true的方法就报异常了,这样两个可能就不知道用哪个了
									throw new BeanCreationException(beanName,
											"Invalid autowire-marked constructors: " + candidates +
											". Found constructor with 'required' Autowired annotation: " +
											candidate);
								}
								requiredConstructor = candidate;
							}
							candidates.add(candidate);//加入集合
						}
						else if (candidate.getParameterCount() == 0) {//是无参构造方法
							defaultConstructor = candidate;
						}
					}
					if (!candidates.isEmpty()) {//如果候选不为空,基本就是有Autowired注解的,转换成数组直接返回
						// Add default constructor to list of optional constructors, as fallback.
						if (requiredConstructor == null) {
							if (defaultConstructor != null) {//添加默认构造函数
								candidates.add(defaultConstructor);
							}
							else if (candidates.size() == 1 && logger.isInfoEnabled()) {
								logger.info("Inconsistent constructor declaration on bean with name '" + beanName +
										"': single autowire-marked constructor flagged as optional - " +
										"this constructor is effectively required since there is no " +
										"default constructor to fall back to: " + candidates.get(0));
							}
						}
						candidateConstructors = candidates.toArray(new Constructor<?>[0]);
					}
					else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
						candidateConstructors = new Constructor<?>[] {rawCandidates[0]};//只有一个函数且有参数
					}
					else if (nonSyntheticConstructors == 2 && primaryConstructor != null &&
							defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
						candidateConstructors = new Constructor<?>[] {primaryConstructor, defaultConstructor};//有两个非合成方法,有优先方法和默认方法,且不相同
					}
					else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {//只有一个优先的
						candidateConstructors = new Constructor<?>[] {primaryConstructor};
					}
					else {//大于2个没注解的构造方法就不知道要用什么了,所以就返回null
						candidateConstructors = new Constructor<?>[0];
					}
					this.candidateConstructorsCache.put(beanClass, candidateConstructors);
				}
			}
		}
		return (candidateConstructors.length > 0 ? candidateConstructors : null);
	}

요약 다음과 같습니다

  • 더가있는 경우 Autowired, requiredtrue또는 기본 생성자없이, 예외가보고됩니다.
  • 오직 하나의 경우 Autowired, requiredfalse, 아니 기본 생성자는 경고가보고됩니다.
  • 당신이 주석을 정의를 autowire가없는 경우 2생성자의 하나 개 이상의 매개 변수를 인수가없는 생성자가 없습니다, 그것은 오류가 있습니다.
  • 다른 경우가있을 수 있지만, 가지고 Autowired생성자 우선 순위를, 기본 생성자입니다.

생성자 파라미터가 존재하고 있으면 호출한다 autowireConstructor에는 실질적 인수없이 생성자가없는 경우가 아니라면, 자동 조립을 Kotlin하는 방법 구성된 우선 순위를 제공 하였다. 그리고 뒤에 자동 조립 기본 생성자의 관점에서 인스턴스화하는 방법.

음, 오늘, 우리는 단지 자신의 학습, 제한 용량 이해를 참조하십시오 위대한 하나님을 뿌리지 마십시오 도움이 연구에 희망과 이해, 용서하십시오.

게시 된 235 개 원래 기사 · 원 찬양 74 ·은 30000 +를 볼

추천

출처blog.csdn.net/wangwei19871103/article/details/105103688