第二次调用Bean后置处理器:第一次推断构造方法
第二次调用Bean后置处理器调用链
createBeanInstance:1210, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
doCreateBean:558, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
createBean:517, AbstractAutowireCapableBeanFactory (org.springframework.beans.factory.support)
lambda$doGetBean
$Lambda$12)
getSingleton:229, DefaultSingletonBeanRegistry (org.springframework.beans.factory.support)
doGetBean:326, AbstractBeanFactory (org.springframework.beans.factory.support)
getBean:200, AbstractBeanFactory (org.springframework.beans.factory.support)
preInstantiateSingletons:854, DefaultListableBeanFactory (org.springframework.beans.factory.support)
finishBeanFactoryInitialization:889, AbstractApplicationContext (org.springframework.context.support)
refresh:553, AbstractApplicationContext (org.springframework.context.support)
main:9, AnnotationConfigApplication (com.tbryant.springtest.demo)
第二次调用Bean后置处理器入口
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
// 拿到目标对象类型
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());
}
// 通过Supplier表达式拿对象,一般为null
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
// 如果有工厂方法,那么就调用工厂方法,不需要spring实例化
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
// 表示创建对象的构造方法是否被解析过
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
// 如果解析过,直接实例化对象
if (resolved) {
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
return instantiateBean(beanName, mbd);
}
}
// Candidate constructors for autowiring?
// 第二次调用后置处理器 入口,推断构造方法
// 有且进有一个带参构造方法的情况下不为null
// 有多个@Autowired(required = false)的构造方法的情况下不为null
// 其他情况都为空
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);
}
ConfigurationClassPostProcessor.determineCandidateConstructors
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) throws BeansException {
return null;
}
AutowiredAnnotationBeanPostProcessor.determineCandidateConstructors
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
throws BeanCreationException {
// Let's check for lookup methods here...
// 处理@Lookup start
if (!this.lookupMethodsChecked.contains(beanName)) {
try {
ReflectionUtils.doWithMethods(beanClass, 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");
}
}
});
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
}
this.lookupMethodsChecked.add(beanName);
}
// 处理@Lookup end
// Quick check on the concurrent map first, with minimal locking.
// 从缓存中拿当前类型对应的构造方法,第一次肯定是null
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);
// 必要的构造方法,required = true
Constructor<?> requiredConstructor = null;
// 默认的构造方法
Constructor<?> defaultConstructor = null;
// 处理Kotlin类,如果是Java类永远返回null
Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
// 非合并构造方法个数,对于Java类没什么用,Kotlin类可能有多个候选构造方法
int nonSyntheticConstructors = 0;
// 遍历所有构造方法
for (Constructor<?> candidate : rawCandidates) {
// 不是合成的构造方法
if (!candidate.isSynthetic()) {
nonSyntheticConstructors++;
}
// 不会进
else if (primaryConstructor != null) {
continue;
}
// 取@Autowired属性
AnnotationAttributes ann = findAutowiredAnnotation(candidate);
if (ann == null) {
Class<?> userClass = ClassUtils.getUserClass(beanClass);
// userClass:CGLib的目标类型
// beanClass:当前类型
// 通常不会进
if (userClass != beanClass) {
try {
Constructor<?> superCtor =
userClass.getDeclaredConstructor(candidate.getParameterTypes());
ann = findAutowiredAnnotation(superCtor);
}
catch (NoSuchMethodException ex) {
// Simply proceed, no equivalent superclass constructor found...
}
}
}
if (ann != null) {
if (requiredConstructor != null) {
throw new BeanCreationException(beanName,
"Invalid autowire-marked constructor: " + candidate +
". Found constructor with 'required' Autowired annotation already: " +
requiredConstructor);
}
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;
}
candidates.add(candidate);
}
// 如果构造方法参数个数为0,spring认为是默认构造方法
else if (candidate.getParameterCount() == 0) {
defaultConstructor = candidate;
}
}
// 有@Autowired注解的构造方法才会进
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));
}
}
candidateConstructors = candidates.toArray(new Constructor<?>[0]);
}
else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
candidateConstructors = new Constructor<?>[] {rawCandidates[0]};
}
// Java类不会进
else if (nonSyntheticConstructors == 2 && primaryConstructor != null && defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
candidateConstructors = new Constructor<?>[] {primaryConstructor, defaultConstructor};
}
// Java类不会进
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);
}
这个方法返回构造方法数组,以下两种情况返回值不为null
- 有且仅有一个带参构造方法,返回那个构造方法
- 有多个@Autowired(required = false)注解的构造方法,返回这些构造方法
@Autowired(required = true)含义:使用此构造方法
@Autowired(required = false)含义:将此构造方法设置为自动装配候选构造方法
第二次推断构造方法
public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
BeanWrapperImpl bw = new BeanWrapperImpl();
this.beanFactory.initBeanWrapper(bw);
// 最终使用的构造函数
Constructor<?> constructorToUse = null;
// 最终使用的构造函数参数(封装)
ArgumentsHolder argsHolderToUse = null;
// 最终使用的构造函数参数
Object[] argsToUse = null;
// explicitArgs 通常为空,解析构造函数参数
if (explicitArgs != null) {
argsToUse = explicitArgs;
}
else {
// 找出来的参数,并不是最终使用构造函数的参数
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) {
// 参数转换,比如给的是string使用的是对象
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 {
// 拿所有构造函数
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()) {
// 唯一候选构造方法
Constructor<?> uniqueCandidate = candidates[0];
if (uniqueCandidate.getParameterCount() == 0) {
synchronized (mbd.constructorArgumentLock) {
mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
mbd.constructorArgumentsResolved = true;
mbd.resolvedConstructorArguments = EMPTY_ARGS;
}
// 调用默认构造方法实例化
bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
return bw;
}
}
// Need to resolve the constructor.
// 是否需要解析构造方法
boolean autowiring = (chosenCtors != null || mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
// 临时存放构造方法参数
ConstructorArgumentValues resolvedValues = null;
// 最小参数数量
int minNrOfArgs;
// explicitArgs 通常为空
if (explicitArgs != null) {
minNrOfArgs = explicitArgs.length;
}
else {
// 拿程序员手动传的参数值
ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
resolvedValues = new ConstructorArgumentValues();
// 计算构造方法最小参数数量
// 把手动配置的构造函数参数放到resolvedValues
minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
}
// 排序 先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.
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;
}
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;
}
// 如果有一个候选构造方法 && 权重值相等,这两个构造方法都属于模糊不清的构造方法,spring不知道用哪个
else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
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");
// 通过推断出来的构造函数反射实例化对象
bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
return bw;
}
手动装配
没有显式提供构造方法:使用默认构造方法
提供一个构造方法:使用该构造方法
提供多个构造方法,包含默认构造方法:使用默认构造方法
提供多个构造方法,不包含默认构造方法:报错
提供多个构造方法,有一个@Autowired(required = true)的构造方法:使用有@Autowired(required = true)的构造方法
提供多个构造方法,有多个@Autowired(required = true)的构造方法:报错
提供多个构造方法,有一个@Autowired(required = true)的构造方法和多个@Autowired(required = false)的构造方法:报错
提供多个构造方法,有多个@Autowired(required = false)的构造方法:使用符合条件的&参数最多的构造方法
使用构造方法自动装配
使用符合条件的&参数最多的构造方法