Spring 得到候选构造方法之后,如何选择使用哪个构造方法?
ConstructorResolver#autowireConstructor
1、定义三个变量
// 最后决定使用的构造方法
Constructor<?> constructorToUse = null;
// 构造函数需要使用的参数持有器
ArgumentsHolder argsHolderToUse = null;
// 最后需要使用的构造方法的参数
Object[] argsToUse = null;
2、explicitArgs 参数代表的是外面getBean传入的参数
AnnotationConfigApplicationContext
context = new AnnotationConfigApplicationContext(MyTest.class);
// 此处getBean后面的参数就是 explicitArgs 参数值
TestService testService = context.getBean("testService", new UserService(), new UserService());
3、如果传入了 explicitArgs值则构造函数的参数就是用传入的参数
if (explicitArgs != null) {
argsToUse = explicitArgs;
}
4、看一下缓存中是否存在
4.1、如果缓存中存在需要使用的构造方法,且当前构造方法需要的参数已经解析过,取出缓存的构造方法需要的参数列表,如果当前参数列表为null,再判断一下是否有需要解析的参数,如果存在需要解析的参数,需要去解析。
Object[] argsToResolve = null;
synchronized (mbd.constructorArgumentLock) {
constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
if (constructorToUse != null && mbd.constructorArgumentsResolved) {
// Found a cached constructor...
argsToUse = mbd.resolvedConstructorArguments;
if (argsToUse == null) {
argsToResolve = mbd.preparedConstructorArguments;
}
}
}
if (argsToResolve != null) {
argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);
}
4.2、 解析参数
4.2.1、ConstructorResolver#resolvePreparedArguments
得到解析器,如果存在则使用指定的解析器,如果不存在则使用默认的解析器
TypeConverter customConverter = this.beanFactory.getCustomTypeConverter();
TypeConverter converter = (customConverter != null ? customConverter : bw);
4.2.2、遍历所有需要解析的参数数组,判断每个需要解析的参数的类型,执行不同的代码逻辑
//
if (argValue == autowiredArgumentMarker) {
argValue = resolveAutowiredArgument(methodParam, beanName, null, converter