栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring构造器的选择

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring构造器的选择

一、源码剖析

1、org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
	    //移除部分代码
	    
	    
	    
		Constructor[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
		if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
			return autowireConstructor(beanName, mbd, ctors, args);
		}

		// Preferred constructors for default construction?
		ctors = mbd.getPreferredConstructors();
		if (ctors != null) {
			return autowireConstructor(beanName, mbd, ctors, null);
		}

		// No special handling: simply use no-arg constructor.
		return instantiateBean(beanName, mbd);
	}

2、determineConstructorsFromBeanPostProcessors调用bean的后置处理器筛选出候选的构造方法,注意此时可能存在多个

public Constructor[] determineCandidateConstructors(Class beanClass, final String beanName)
			throws BeanCreationException {

		// Let's check for lookup methods here...
		//省略构造方法中存在lookup相关代码

		// 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 {
						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);
					}
					//存所有@Autowired属性的构造方法
					List> candidates = new ArrayList<>(rawCandidates.length);
					//标记构造器存在@Autowired注解且存在required属性为true,因为类的构造器中所有@Autowired注解中只允许存在一个为true,且不允许存在required为false构造方法负责报错
					Constructor requiredConstructor = null;
					Constructor defaultConstructor = null;
					Constructor 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) {
						    //当前构造器不存在@Autowired注解、会回去父类的构造器
							Class userClass = ClassUtils.getUserClass(beanClass);
							if (userClass != beanClass) {
								try {
									Constructor superCtor =
											userClass.getDeclaredConstructor(candidate.getParameterTypes());
											//继续判断父类的该构造器
									ann = findAutowiredAnnotation(superCtor);
								}
								catch (NoSuchMethodException ex) {
									// Simply proceed, no equivalent superclass constructor found...
								}
							}
						}
						//构造器存在@Autowired注解
						if (ann != null) {
							if (requiredConstructor != null) {
								throw new BeanCreationException(beanName,
										"Invalid autowire-marked constructor: " + candidate +
										". Found constructor with 'required' Autowired annotation already: " +
										requiredConstructor);
							}
							//查看@Autowired注解的required属性是否为true
							boolean required = determineRequiredStatus(ann);
							if (required) {
							     
								if (!candidates.isEmpty()) {
									throw new BeanCreationException(beanName,
											"Invalid autowire-marked constructors: " + candidates +
											". Found constructor with 'required' Autowired annotation: " +
											candidate);
								}
								requiredConstructor = candidate;
							}
							//把该构造器放入集合,注意该构造器是@Autowired修饰的
							candidates.add(candidate);
						}
						else if (candidate.getParameterCount() == 0) {
						    //无参的构造器设置默认构造器属性
							defaultConstructor = candidate;
						}
					}
					
					if (!candidates.isEmpty()) {
						// 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));
							}
						}
						//所有@Autowired、无参的构造方法
						candidateConstructors = candidates.toArray(new Constructor[0]);
					}
					//只找到一个且不是无参的没有@Autowired修饰的,返回
					else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
						candidateConstructors = new Constructor[] {rawCandidates[0]};
					}
					//Kotlin相关
					else if (nonSyntheticConstructors == 2 && primaryConstructor != null &&
							defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
						candidateConstructors = new Constructor[] {primaryConstructor, defaultConstructor};
					}
					//Kotlin相关
					else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
						candidateConstructors = new Constructor[] {primaryConstructor};
					}
					else {
						candidateConstructors = new Constructor[0];
					}
					this.candidateConstructorsCache.put(beanClass, candidateConstructors);
				}
			}
		}
		return (candidateConstructors.length > 0 ? candidateConstructors : null);
	}

总结:

3、当步骤2中返回的构造方法不为Null时、getResolvedAutowireMode默认true、通过bean定义指定的构造方法的参数、通过getBean设置的参数

(1)bean定义设置的参数

            GenericBeanDefinition  beanDefinition1=new GenericBeanDefinition();
            beanDefinition1.getConstructorArgumentValues().addGenericArgumentValue(new OrderService());

(2)通过annotationConfigApplicationContext.getBean(UserService.class,new OrderService());

		if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
				mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
			return autowireConstructor(beanName, mbd, ctors, args);
		}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1032601.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号