创建bean实例(createBeanInstance 方法)
AbstractAutowireCapableBeanFactory 的 createBeanInstance 方法实现了创建 bean 的实例,将 BeanDefinition 转换为 BeanWrapper,转换是一个复杂的过程,大致步骤如下:
1)、如果存在创建bean的回调方法,则从回调方法获取bean实例 BeanWrapper
2)、如果存在工厂方法则使用工厂方法创建bean实例 BeanWrapper
3)、一个类中有多个构造方法,每个构造函数都有不同的参数,所以需要根据参数决定构造方法并进行bean实例的创建
4)、如果既不存在工厂方法也不存在带参数的构造方法,则使用无参默认构造方法进行bean实例的创建
createBeanInstance 方法源码如下:
// AbstractAutowireCapableBeanFactory 的 createBeanInstance 方法
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
// 解析beanClass
Class<?> beanClass = resolveBeanClass(mbd, beanName);
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}
// 获取创建bean时的回调方法 callback
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
// 从回调方法获取bean实例 BeanWrapper
return obtainFromSupplier(instanceSupplier, beanName);
}
// factoryMethodName 属性存在或者xml中配置了 factory-method 属性
if (mbd.getFactoryMethodName() != null) {
// 使用工厂方法创建bean实例 BeanWrapper
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
// resolvedConstructorOrFactoryMethod 存放已经解析好的bean的构造方法(多个不同参数的构造方法)或者对应的工厂方法
if (mbd.resolvedConstructorOrFactoryMethod != null) {
// 已经解析过了
resolved = true;
// 是否需要根据参数来决定构造方法
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
// bean中存在多个构造方法,需要根据参数决定构造方法来创建bean实例 BeanWrapper
return autowireConstructor(beanName, mbd, null, null);
}
else {
// 无参默认构造方法创建bean实例 BeanWrapper
return instantiateBean(beanName, mbd);
}
}
// Candidate constructors for autowiring?
// 还没有解析bean的构造方法,这里决定构造方法
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
// 根据参数决定构造方法来创建bean实例 BeanWrapper
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.
// 无参默认构造方法创建bean实例 BeanWrapper
return instantiateBean(beanName, mbd);
}
1.1 从回调方法获取bean实例 BeanWrapper
从回调方法获取bean实例 BeanWrapper 入口在 AbstractAutowireCapableBeanFactory 的 obtainFromSupplier 方法,源码如下:
// AbstractAutowireCapableBeanFactory 的 obtainFromSupplier 方法
protected BeanWrapper obtainFromSupplier(Supplier<?> instanceSupplier, String beanName) {
Object instance;
String outerBean = this.currentlyCreatedBean.get();
this.currentlyCreatedBean.set(beanName);
try {
// 回调方法获取返回对象
instance = instanceSupplier.get();
}
finally {
// 更新线程 ThreadLocal 缓存数据
if (outerBean != null) {
this.currentlyCreatedBean.set(outerBean);
}
else {
this.currentlyCreatedBean.remove();
}
}
if (instance == null) {
// instance 为空时,创建 NullBean
instance = new NullBean();
}
// 构建 BeanWrapper
BeanWrapper bw = new BeanWrapperImpl(instance);
// 初始化BeanWrapper,即 BeanWrapper 设置 ConversionService 属性,注册属性编辑器
initBeanWrapper(bw);
return bw;
}
1.2 使用工厂方法创建bean实例 BeanWrapper
使用工厂方法创建bean实例 BeanWrapper 入口在 AbstractAutowireCapableBeanFactory 的 instantiateUsingFactoryMethod 方法,源码如下:
// 1、AbstractAutowireCapableBeanFactory 的 instantiateUsingFactoryMethod 方法
protected BeanWrapper instantiateUsingFactoryMethod(
String beanName, RootBeanDefinition mbd, @Nullable Object[] explicitArgs) {
// 调用 ConstructorResolver 的 instantiateUsingFactoryMethod 方法创建bean实例 BeanWrapper
return new ConstructorResolver(this).instantiateUsingFactoryMethod(beanName, mbd, explicitArgs);
}
// 2、ConstructorResolver 的 instantiateUsingFactoryMethod 方法
public BeanWrapper instantiateUsingFactoryMethod(
String beanName, RootBeanDefinition mbd, @Nullable Object[] explicitArgs) {
// 构造BeanWrapper并初始化BeanWrapper(设置 ConversionService 和 注册属性编辑器)
BeanWrapperImpl bw = new BeanWrapperImpl();
this.beanFactory.initBeanWrapper(bw);
Object factoryBean;
Class<?> factoryClass;
boolean isStatic;
String factoryBeanName = mbd.getFactoryBeanName();
if (factoryBeanName != null) {
if (factoryBeanName.equals(beanName)) {
// factoryBeanName 和 beanName 相同,抛出异常
throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
"factory-bean reference points back to the same bean definition");
}
// 根据factoryBeanName获取 FactoryBean
factoryBean = this.beanFactory.getBean(factoryBeanName);
if (mbd.isSingleton() && this.beanFactory.containsSingleton(beanName)) {
throw new ImplicitlyAppearedSingletonException();
}
factoryClass = factoryBean.getClass();
isStatic = false;
}
else {
// It's a static factory method on the bean class.
// bean 的静态的工厂方法
if (!mbd.hasBeanClass()) {
// BeanDefinition 既没有声明 beanClass 也没有声明 factoryBean 的引用
throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
"bean definition declares neither a bean class nor a factory-bean reference");
}
factoryBean = null;
factoryClass = mbd.getBeanClass();
isStatic = true;
}
// 要使用的工厂方法
Method factoryMethodToUse = null;
ArgumentsHolder argsHolderToUse = null;
// 要使用的参数
Object[] argsToUse = null;
if (explicitArgs != null) {
argsToUse = explicitArgs;
}
else {
Object[] argsToResolve = null;
synchronized (mbd.constructorArgumentLock) {
factoryMethodToUse = (Method) mbd.resolvedConstructorOrFactoryMethod;
if (factoryMethodToUse != null && mbd.constructorArgumentsResolved) {
// Found a cached factory method...
argsToUse = mbd.resolvedConstructorArguments;
if (argsToUse == null) {
argsToResolve = mbd.preparedConstructorArguments;
}
}
}
if (argsToResolve != null) {
// 解析存储在 BeanDefinition 中准备好的参数
argsToUse = resolvePreparedArguments(beanName, mbd, bw, factoryMethodToUse, argsToResolve, true);
}
}
if (factoryMethodToUse == null || argsToUse == null) {
// Need to determine the factory method...
// Try all methods with this name to see if they match the given arguments.
// 选择出工厂方法,尝试使用此名称的所有方法,看看它们是否与给定的参数匹配。
factoryClass = ClassUtils.getUserClass(factoryClass);
List<Method> candidateList = null;
if (mbd.isFactoryMethodUnique) {
// 存在多个工厂方法
if (factoryMethodToUse == null) {
factoryMethodToUse = mbd.getResolvedFactoryMethod();
}
if (factoryMethodToUse != null) {
candidateList = Collections.singletonList(factoryMethodToUse);
}
}
if (candidateList == null) {
candidateList = new ArrayList<>();
Method[] rawCandidates = getCandidateMethods(factoryClass, mbd);
for (Method candidate : rawCandidates) {
// 遍历Bean中定义的所有方法,选择出不仅是static而且是工厂方法的方法
if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate)) {
candidateList.add(candidate);
}
}
}
if (candidateList.size() == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
Method uniqueCandidate = candidateList.get(0);
if (uniqueCandidate.getParameterCount() == 0) {
// 只有一个无参的工厂方法
mbd.factoryMethodToIntrospect = uniqueCandidate;
synchronized (mbd.constructorArgumentLock) {
mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
mbd.constructorArgumentsResolved = true;
mbd.resolvedConstructorArguments = EMPTY_ARGS;
}
// instantiate 方法中调用 BeanFactory 的实例策略(默认是 SimpleInstantiationStrategy)的 instantiate 方法创建bean实例,
// 具体就是通过反射,即调用 Method 的 invoke 方法生成bean实例,和 new XXX() 同等效果
bw.setBeanInstance(instantiate(beanName, mbd, factoryBean, uniqueCandidate, EMPTY_ARGS));
return bw;
}
}
Method[] candidates = candidateList.toArray(new Method[0]);
AutowireUtils.sortFactoryMethods(candidates);
ConstructorArgumentValues resolvedValues = null;
boolean autowiring = (mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
int minTypeDiffWeight = Integer.MAX_VALUE;
Set<Method> ambiguousFactoryMethods = null;
// 构造方法最少参数个数
int minNrOfArgs;
if (explicitArgs != null) {
minNrOfArgs = explicitArgs.length;
}
else {
// We don't have arguments passed in programmatically, so we need to resolve the
// arguments specified in the constructor arguments held in the bean definition.
// BeanDefinition 中存在构造参数
if (mbd.hasConstructorArgumentValues()) {
ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
resolvedValues = new ConstructorArgumentValues();
// 解析构造参数
minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
}
else {
minNrOfArgs = 0;
}
}
LinkedList<UnsatisfiedDependencyException> causes = null;
for (Method candidate : candidates) {
Class<?>[] paramTypes = candidate.getParameterTypes();
// 方法参数大于等于最少构造参数个数
if (paramTypes.length >= minNrOfArgs) {
ArgumentsHolder argsHolder;
if (explicitArgs != null) {
// Explicit arguments given -> arguments length must match exactly.
if (paramTypes.length != explicitArgs.length) {
continue;
}
// 要求的参数个数和方法参数个数相同
argsHolder = new ArgumentsHolder(explicitArgs);
}
else {
// Resolved constructor arguments: type conversion and/or autowiring necessary.
try {
String[] paramNames = null;
ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
if (pnd != null) {
paramNames = pnd.getParameterNames(candidate);
}
argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw,
paramTypes, paramNames, candidate, autowiring, candidates.length == 1);
}
catch (UnsatisfiedDependencyException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Ignoring factory method [" + candidate + "] of bean '" + beanName + "': " + ex);
}
// Swallow and try next overloaded factory method.
if (causes == null) {
causes = new LinkedList<>();
}
// 记录每个方法解析构造参数时的异常
causes.add(ex);
continue;
}
}
int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
// Choose this factory method if it represents the closest match.
if (typeDiffWeight < minTypeDiffWeight) {
factoryMethodToUse = candidate;
argsHolderToUse = argsHolder;
argsToUse = argsHolder.arguments;
minTypeDiffWeight = typeDiffWeight;
ambiguousFactoryMethods = null;
}
// Find out about ambiguity: In case of the same type difference weight
// for methods with the same number of parameters, collect such candidates
// and eventually raise an ambiguity exception.
// However, only perform that check in non-lenient constructor resolution mode,
// and explicitly ignore overridden methods (with the same parameter signature).
else if (factoryMethodToUse != null && typeDiffWeight == minTypeDiffWeight &&
!mbd.isLenientConstructorResolution() &&
paramTypes.length == factoryMethodToUse.getParameterCount() &&
!Arrays.equals(paramTypes, factoryMethodToUse.getParameterTypes())) {
if (ambiguousFactoryMethods == null) {
ambiguousFactoryMethods = new LinkedHashSet<>();
ambiguousFactoryMethods.add(factoryMethodToUse);
}
// 记录多个工厂方法
ambiguousFactoryMethods.add(candidate);
}
}
}
if (factoryMethodToUse == null || argsToUse == null) {
if (causes != null) {
UnsatisfiedDependencyException ex = causes.removeLast();
for (Exception cause : causes) {
this.beanFactory.onSuppressedException(cause);
}
// 存在异常,这里直接抛出异常
throw ex;
}
List<String> argTypes = new ArrayList<>(minNrOfArgs);
if (explicitArgs != null) {
for (Object arg : explicitArgs) {
argTypes.add(arg != null ? arg.getClass().getSimpleName() : "null");
}
}
else if (resolvedValues != null) {
Set<ValueHolder> valueHolders = new LinkedHashSet<>(resolvedValues.getArgumentCount());
valueHolders.addAll(resolvedValues.getIndexedArgumentValues().values());
valueHolders.addAll(resolvedValues.getGenericArgumentValues());
for (ValueHolder value : valueHolders) {
String argType = (value.getType() != null ? ClassUtils.getShortName(value.getType()) :
(value.getValue() != null ? value.getValue().getClass().getSimpleName() : "null"));
argTypes.add(argType);
}
}
String argDesc = StringUtils.collectionToCommaDelimitedString(argTypes);
// 没有找到匹配的工厂方法
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"No matching factory method found: " +
(mbd.getFactoryBeanName() != null ?
"factory bean '" + mbd.getFactoryBeanName() + "'; " : "") +
"factory method '" + mbd.getFactoryMethodName() + "(" + argDesc + ")'. " +
"Check that a method with the specified name " +
(minNrOfArgs > 0 ? "and arguments " : "") +
"exists and that it is " +
(isStatic ? "static" : "non-static") + ".");
}
else if (void.class == factoryMethodToUse.getReturnType()) {
// 工厂返回值为void,抛出异常
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Invalid factory method '" + mbd.getFactoryMethodName() +
"': needs to have a non-void return type!");
}
else if (ambiguousFactoryMethods != null) {
// 存在多个工厂方法,抛出异常
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Ambiguous factory method matches found in bean '" + beanName + "' " +
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " +
ambiguousFactoryMethods);
}
if (explicitArgs == null && argsHolderToUse != null) {
mbd.factoryMethodToIntrospect = factoryMethodToUse;
argsHolderToUse.storeCache(mbd, factoryMethodToUse);
}
}
// BeanWrapper 设置bean实例
// instantiate 方法中调用 BeanFactory 的实例策略(默认是 SimpleInstantiationStrategy)的 instantiate 方法创建bean实例,
// 具体就是通过反射,即调用 Method 的 invoke 方法生成bean实例,和 new XXX() 同等效果
bw.setBeanInstance(instantiate(beanName, mbd, factoryBean, factoryMethodToUse, argsToUse));
return bw;
}
工厂方法创建bean实例时最终调用的是 BeanFactory 的实例策略(默认是 SimpleInstantiationStrategy)的 instantiate 方法,通过反射,即调用 Method 的 invoke 方法生成bean实例,和 new XXX() 同等效果
1.3 带参数的构造方法创建bean实例 BeanWrapper
带参数的构造方法创建bean实例 BeanWrapper 过程比较复杂,下面我们通过源码分析一下其过程,入口在 AbstractAutowireCapableBeanFactory 的 autowireConstructor 方法,源码如下:
// 1、AbstractAutowireCapableBeanFactory 的 autowireConstructor 方法
protected BeanWrapper autowireConstructor(
String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) {
// 调用 ConstructorResolver 的 autowireConstructor 方法创建bean实例
return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
}
// 2、ConstructorResolver 的 autowireConstructor 方法
public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
@Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
// 构建 BeanWrapper并初始化BeanWrapper
BeanWrapperImpl bw = new BeanWrapperImpl();
this.beanFactory.initBeanWrapper(bw);
Constructor<?> constructorToUse = null;
ArgumentsHolder argsHolderToUse = null;
Object[] argsToUse = null;
if (explicitArgs != null) {
// 通过getBean方法调用时传入的参数
argsToUse = explicitArgs;
}
else {
// 从配置文件中bean的定义解析参数和构造方法
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) {
// xml配置文件中定义的构造方法参数
argsToResolve = mbd.preparedConstructorArguments;
}
}
}
if (argsToResolve != null) {
// 解析参数类型,比如给定的构造方法 X(int,int)通过此方法后就会将xml配置的 X("1","1") 转换为 X(1,1)
argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve, true);
}
}
// 构造方法或者参数没有被缓存
if (constructorToUse == null || argsToUse == null) {
// Take specified constructors, if any.
// 传入的指定构造方法
Constructor<?>[] candidates = chosenCtors;
if (candidates == null) {
Class<?> beanClass = mbd.getBeanClass();
try {
// 获取bean中所有定义的构造方法
candidates = (mbd.isNonPublicAccessAllowed() ?
beanClass.getDeclaredConstructors() : beanClass.getConstructors());
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Resolution of declared constructors on bean Class [" + beanClass.getName() +
"] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
}
}
if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
// 只有一个构造方法 && 创建bean实例要求的构造参数是空 && BeanDefinition 中没有构造参数值
Constructor<?> uniqueCandidate = candidates[0];
if (uniqueCandidate.getParameterCount() == 0) {
// 该构造方法是无参的
synchronized (mbd.constructorArgumentLock) {
// BeanDefinition 中关于构造方法和构造参数的缓存更新
mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
mbd.constructorArgumentsResolved = true;
mbd.resolvedConstructorArguments = EMPTY_ARGS;
}
// instantiate方法最终调用的是 BeanFactory 的实例策略(默认是 SimpleInstantiationStrategy)的 instantiate 方法,分为两种情况:
// 1)、没有 override 方法时,调用 Constructor 的 newInstance 方法 或者 KotlinDelegate 的 instantiateClass 方法生成实例bean
// 2)、有 override 方法时,SimpleInstantiationStrategy 策略不支持创建bean实例,CglibSubclassingInstantiationStrategy 策略使用CGLIB代理创建bean实例
bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
return bw;
}
}
// Need to resolve the constructor.
// 是否需要解析构造方法标识(chosenCtors 不为null 或者 resolvedAutowireMode 是构造方法注入)
boolean autowiring = (chosenCtors != null ||
mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
ConstructorArgumentValues resolvedValues = null;
int minNrOfArgs;
if (explicitArgs != null) {
minNrOfArgs = explicitArgs.length;
}
else {
ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
// 存放解析后的参数值
resolvedValues = new ConstructorArgumentValues();
// 能解析到的参数值的个数
minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
}
// 构造方法排序,public 构造方法优先,同 public 按照参数个数倒序,非public次之,同 非public 按照参数个数倒序
AutowireUtils.sortConstructors(candidates);
int minTypeDiffWeight = Integer.MAX_VALUE;
Set<Constructor<?>> ambiguousConstructors = null;
LinkedList<UnsatisfiedDependencyException> causes = null;
// 遍历所有的构造方法
for (Constructor<?> candidate : candidates) {
Class<?>[] paramTypes = candidate.getParameterTypes();
if (constructorToUse != null && argsToUse != null && argsToUse.length > paramTypes.length) {
// Already found greedy constructor that can be satisfied ->
// do not look any further, there are only less greedy constructors left.
// 如果已经找到了 constructorToUse 和 argsToUse,并且 argsToUse 参数个数大于 当前构造方法参数个数,则表示找到了要使用的构造方法
// 原因是构造方法已经按照参数个数倒序排序了,说明此时已经找到了参数最多的构造方法了
break;
}
if (paramTypes.length < minNrOfArgs) {
// 构造方法参数类型个数小于需要的参数个数,继续遍历寻找
continue;
}
ArgumentsHolder argsHolder;
if (resolvedValues != null) {
// 配置文件中有构造方法的参数
try {
// 获取注释上的参数名称
String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, paramTypes.length);
if (paramNames == null) {
// 参数名称查找器
ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
if (pnd != null) {
// 获取当前构造方法的参数名称
paramNames = pnd.getParameterNames(candidate);
}
}
// 根据参数名称和参数类型构建参数持有者
argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
}
catch (UnsatisfiedDependencyException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
}
// Swallow and try next constructor.
if (causes == null) {
causes = new LinkedList<>();
}
// 记录创建参数持有者过程中的异常
causes.add(ex);
continue;
}
}
else {
// Explicit arguments given -> arguments length must match exactly.
if (paramTypes.length != explicitArgs.length) {
// 个数不相等,继续遍历寻找
continue;
}
// 使用getBean传参的参数构造参数持有者
argsHolder = new ArgumentsHolder(explicitArgs);
}
// 检测是否有不确定性的构造方法存在,例如:不同构造方法的参数为父子关系
int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
// Choose this constructor if it represents the closest match.
if (typeDiffWeight < minTypeDiffWeight) {
// 表示当前最接近的匹配,选择作为构造方法
constructorToUse = candidate;
argsHolderToUse = argsHolder;
argsToUse = argsHolder.arguments;
minTypeDiffWeight = typeDiffWeight;
ambiguousConstructors = null;
}
else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
// 匹配度相同的构造方法,记录在 ambiguousConstructors 集合中
if (ambiguousConstructors == null) {
ambiguousConstructors = new LinkedHashSet<>();
ambiguousConstructors.add(constructorToUse);
}
ambiguousConstructors.add(candidate);
}
}
if (constructorToUse == null) {
// 遍历了所有的构造方法,也没有找到匹配的构造方法
if (causes != null) {
UnsatisfiedDependencyException ex = causes.removeLast();
for (Exception cause : causes) {
this.beanFactory.onSuppressedException(cause);
}
throw ex;
}
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Could not resolve matching constructor " +
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
}
else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
// 具有多个匹配度一样的重复构造方法,抛出异常
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Ambiguous constructor matches found in bean '" + beanName + "' " +
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " +
ambiguousConstructors);
}
if (explicitArgs == null && argsHolderToUse != null) {
// 缓存构造方法和构造参数
argsHolderToUse.storeCache(mbd, constructorToUse);
}
}
Assert.state(argsToUse != null, "Unresolved constructor arguments");
// 根据找到的构造方法和构造参数创建bean实例,并设置到 BeanWrapper 中
bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
return bw;
}
// 3、ConstructorResolver 的 instantiate 方法
private Object instantiate(
String beanName, RootBeanDefinition mbd, Constructor<?> constructorToUse, Object[] argsToUse) {
try {
// 获取 BeanFactory 中的实例化策略
InstantiationStrategy strategy = this.beanFactory.getInstantiationStrategy();
if (System.getSecurityManager() != null) {
return AccessController.doPrivileged((PrivilegedAction<Object>) () ->
strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse),
this.beanFactory.getAccessControlContext());
}
else {
// 模板方法,调用具体实现策略的 instantiate,默认是 SimpleInstantiationStrategy 策略
return strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean instantiation via constructor failed", ex);
}
}
// 4、SimpleInstantiationStrategy 的 instantiate
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
final Constructor<?> ctor, Object... args) {
if (!bd.hasMethodOverrides()) {
// 没有配置 replace 或者 lookup 方法
if (System.getSecurityManager() != null) {
// use own privileged to change accessibility (when security is on)
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
ReflectionUtils.makeAccessible(ctor);
return null;
});
}
// 使用 Spring 的反射方法创建bean实例
return BeanUtils.instantiateClass(ctor, args);
}
else {
// BeanDefinition 有 replace 或者 lookup 方法
// SimpleInstantiationStrategy 的 instantiateWithMethodInjection 方法不支持这种创建方式直接抛异常,
// 子类可以覆盖该方法,比如 CglibSubclassingInstantiationStrategy ,它的 instantiateWithMethodInjection 方法通过 CGLIB 代理方式创建bean实例
return instantiateWithMethodInjection(bd, beanName, owner, ctor, args);
}
}
上述代码实现的逻辑比较复杂,其中最核心的就是如何选择构造方法和构造参数的,步骤如下:
1)、如果getBean方法有明确的传参,则先根据传参解析匹配bean中定义的所有构造方法,确定了构造方法后,根据BeanFactory中设置的实例化策略创建bean实例
2)、没有传参时,如果 BeanDefinition 中已经存在解析好的构造方法和构造参数时,则根据BeanFactory中设置的实例化策略创建bean实例
3)、没有传参 && BeanDefinition 中没有解析好的构造方法或者构造参数时,则先根据配置中的参数解析匹配bean中定义的所有构造方法,确定了构造方法后,根据BeanFactory中设置的实例化策略创建bean实例
4)、匹配构造方法遵循了优先匹配 public 构造方法,同 public 构造方法优先匹配参数多的原则
1.4 默认构造方法创建bean实例
如果既不存在工厂方法也不存在带参数的构造方法,则使用无参默认构造方法进行bean实例的创建,入口在 AbstractAutowireCapableBeanFactory 的 instantiateBean 方法,源码如下:
// 1、AbstractAutowireCapableBeanFactory 的 instantiateBean 方法
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this;
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
getInstantiationStrategy().instantiate(mbd, beanName, parent),
getAccessControlContext());
}
else {
// 调用 BeanFactory 中设置的具体实例化策略的 instantiate 方法创建bean实例,默认策略是 SimpleInstantiationStrategy
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
// 构建 BeanWrapper 并初始化 BeanWrapper
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}
// 2、SimpleInstantiationStrategy 的 instantiate 方法
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// Don't override the class with CGLIB if no overrides.
if (!bd.hasMethodOverrides()) {
// 没有配置 replace 或者 lookup
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) {
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
if (System.getSecurityManager() != null) {
constructorToUse = AccessController.doPrivileged(
(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
}
else {
constructorToUse = clazz.getDeclaredConstructor();
}
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
// 使用反射创建bean实例
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// Must generate CGLIB subclass.
// SimpleInstantiationStrategy 不支持这种方式创建bean实例直接抛出异常,但是 CglibSubclassingInstantiationStrategy 策略覆盖了此方法,实现了创建bean实例逻辑
// 如果有需要覆盖或者动态替换的方法时,必须使用 CGLIB 动态代理方式创建bean实例,因为CGLIB在创建代理bean实例时会同时将动态方法织入类中,
// 使用CGLIB将包含replace或者lookup两个特性所对应的的逻辑设置到增强器中,这样才能保证方法调用时会被相应的拦截器拦截增强,
// 返回值为包含拦截器增强的代理bean实例
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
// 3、BeanUtils 的 instantiateClass 方法
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
Assert.notNull(ctor, "Constructor must not be null");
try {
ReflectionUtils.makeAccessible(ctor);
if (KotlinDetector.isKotlinReflectPresent() && KotlinDetector.isKotlinType(ctor.getDeclaringClass())) {
// KotlinDetector 类型的bean,直接使用 kotlin 方式创建bean实例
return KotlinDelegate.instantiateClass(ctor, args);
}
else {
Class<?>[] parameterTypes = ctor.getParameterTypes();
Assert.isTrue(args.length <= parameterTypes.length, "Can't specify more arguments than constructor parameters");
Object[] argsWithDefaultValues = new Object[args.length];
for (int i = 0 ; i < args.length; i++) {
if (args[i] == null) {
Class<?> parameterType = parameterTypes[i];
argsWithDefaultValues[i] = (parameterType.isPrimitive() ? DEFAULT_TYPE_VALUES.get(parameterType) : null);
}
else {
argsWithDefaultValues[i] = args[i];
}
}
// 反射构造实例化对象
return ctor.newInstance(argsWithDefaultValues);
}
}
catch (InstantiationException ex) {
throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
}
catch (IllegalAccessException ex) {
throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
}
catch (IllegalArgumentException ex) {
throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
}
catch (InvocationTargetException ex) {
throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
}
}
// 4、CglibSubclassingInstantiationStrategy 的 instantiateWithMethodInjection 方法
@Override
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
return instantiateWithMethodInjection(bd, beanName, owner, null);
}
@Override
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
@Nullable Constructor<?> ctor, Object... args) {
// Must generate CGLIB subclass...
// 创建 CglibSubclassCreator ,调用其 instantiate 方法创建bean实例
return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
}
// 5、CglibSubclassCreator(CglibSubclassingInstantiationStrategy 内部类) 的 instantiate 方法
public Object instantiate(@Nullable Constructor<?> ctor, Object... args) {
// 创建 Enhancer 对象,并设置其相关属性
Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
Object instance;
if (ctor == null) {
// 没有构造方法时,直接使用反射构造法创建bean实例
instance = BeanUtils.instantiateClass(subclass);
}
else {
try {
// 获取构造器
Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
// 使用构造器构造bean实例
instance = enhancedSubclassConstructor.newInstance(args);
}
catch (Exception ex) {
throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
"Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
}
}
// SPR-10785: set callbacks directly on the instance instead of in the
// enhanced class (via the Enhancer) in order to avoid memory leaks.
Factory factory = (Factory) instance;
// 直接将 callbacks 值设置到实例bean属性中而没有设置到 Enhancer 对象属性中时为了避免内存泄露
factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
// Lookup 方法拦截器
new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
// Replace 方法拦截器
new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
return instance;
}
使用默认构造方法创建bean实例其实就是根据BeanFactory中设置的实例化策略创建bean实例 ,具体逻辑如下:
1)、首先从 BeanFactory 中获取设置的实例化策略,默认策略是 SimpleInstantiationStrategy
2)、没有配置 replace 或者 lookup 方法时,使用反射构造方创建bean实例
3)、配置了replace 或者 lookup 方法时,使用 CglibSubclassingInstantiationStrategy 策略来创建bean实例,CglibSubclassingInstantiationStrategy 使用 CGLIB 动态代理创建bean实例时会织入 LookupOverrideMethodInterceptor 和 ReplaceOverrideMethodInterceptor 拦截器增强,这样在调用时就可以使用代理增强处理逻辑了