准备工厂,然后调用invokeBeanFactoryPostProcessor去解析注解类,把他们分类放到Map当中,再调用registerBeanPostProcessor注册Bean的后置处理器,如果加了开启AOP的@EnableAspectJAutoProxy注解的话是8个,没加是7个。然后实例化所有剩余的非延迟的单例Bean,也就是Spring添加的后置处理器和扫描我们提供的类,在实例化我们单例Bean的过程当中,会在9个地方分别执行5个后置处理器。 好,接下来看一下在哪些地方执行的后置处理器:
1、AbstractAutowireCapableBeanFactory 500
InstantiationAwareBeanPostProcessor # postProcessBeforeInstantiation
在Bean没有开始实例化之前执行
经典应用场景:Spring AOP的时候,他会判断我们的类需不需要增强,百分百不需要增强他会把它放到一个map当中,在后续增强的时候就会忽略掉这个map当中的类。
怎么判断呢?就是看有没有加这些注解。
2、AbstractAutowireCapableBeanFactory 类中 1196 行左右
SmartInstantiationAwareBeanPostProcessor # determineCandidateConstructors
推断构造方法
部分源代码:
/**
* Create a new instance for the specified bean, using an appropriate instantiation strategy:
* factory method, constructor autowiring, or simple instantiation.
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @param args explicit arguments to use for constructor or factory method invocation
* @return a BeanWrapper for the new instance
* @see #obtainFromSupplier
* @see #instantiateUsingFactoryMethod
* @see #autowireConstructor
* @see #instantiateBean
*/
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);
/**
* 检测一个类的访问权限spring默认情况下对于非public的类是允许访问的。
*/
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<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
/**
* 如果工厂方法不为空,则通过工厂方法构建 bean 对象
* OrderService没有放到容器当中,拿到的是return new xxx();这个对象
* 这种构建 bean 的方式如上—基于xml
* 源码就不做深入分析了——基于xml的
*/
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
/**
* 从spring的原始注释可以知道这个是一个Shortcut,什么意思呢?
* 当多次构建同一个 bean 时,可以使用这个Shortcut,
* 也就是说不在需要多次推断应该使用哪种方式构造bean
* 比如在多次构建同一个prototype类型的 bean 时,就可以走此处的hortcut
* 这里的 resolved 和 mbd.constructorArgumentsResolved 将会在 bean 第一次实例
* 化的过程中被设置,后面来证明
*/
//表示创建bena的构造方法没有被解析过
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
/**
* 表示已经找到创建对象的方式
* 第一次肯定为null,然后下面开始推断构造方法
* 原型的时候才有可能不为null
*/
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
//如果已经解析了构造方法的参数,则必须要通过一个带参构造方法来实例
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
// 通过构造方法自动装配的方式构造 bean 对象
return autowireConstructor(beanName, mbd, null, null);
}
else {
//通过默认的无参构造方法进行
return instantiateBean(beanName, mbd);
}
}
/* 第二次执行后置处理器 SmartInstantiationAwareBeanPostProcessor */
// Candidate constructors for autowiring?
//由后置处理器决定返回哪些构造方法
/**
* 如果你提供一个默认构造方法,这儿ctors返回null,
* 因为默认构造方法他会走下面进行初始化,有参构造方法他会走这个if
* 你可以提供一个无参构造方法打断点跟进去调试,里面很多判断
*
* 如果你提供一个无参和一个有参,他返回还是null,为什么呢?
* 因为他判断你是两个构造方法,并且有一个设置成主要的构造方法,
* 并且这个主要的构造方法还不等于默认的构造方法,才会进这个if判断
* 因为你不提供,Spring不知道用哪个,所以就按默认的,返回null
* nonSyntheticConstructors == 2 && primaryConstructor != null &&
* defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)
*
* 1、默认是不自动注入,
* 如果你只提供一个无参的,它还是推断为null;
* 只提供一个无参的,返回null;
* 只提供一个有参的,会推断出来;
* 不提供无参,提供多个有参会报错;
* 提供多个包括无参,返回null;
* 2、如果是自动装配,他会扫描出所有构造方法,
* 如果构造方法都加了@Autowired(required = true),会报异常;
* 如果都加了@Autowired(required = false)它会都返回出来,然后再次推断找一个最优的
* 最优的(无参和参数最多比较特殊),可能想合理的利用spring容器中的这些Bean。
*/
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
/**
* mbd.hasConstructorArgumentValues()构造函数参数值为true
*/
//确定构造方法和构造方法的参数值
return autowireConstructor(beanName, mbd, ctors, args);
}
// No special handling: simply use no-arg constructor.
//使用默认的无参构造方法进行初始化
return instantiateBean(beanName, mbd);
}
@Override
@Nullable
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
throws BeanCreationException {
// Let's check for lookup methods here..
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);
}
//表示已经检查过,不是有lookup,如果有的话上面lookup!=null已经处理
this.lookupMethodsChecked.add(beanName);
}
// Quick check on the concurrent map first, with minimal locking.
// 从缓存中拿?因为Spring只有一个容器,你有可能refresh了两遍。
/**
* 单例原型都不会,配置类没有加@Configuration
* 在当中A(){ B();} B();创建两遍的时候
*/
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;
// 把推断主要的构造方法委托给 Kotlin,非Kotlin的类永远返回null
// primaryConstructor是Kotlin专属的使用对象,java直接忽略
Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
int nonSyntheticConstructors = 0;
for (Constructor<?> candidate : rawCandidates) {
// class里面的方法,判断是不是混合类
if (!candidate.isSynthetic()) {
nonSyntheticConstructors++;
}
else if (primaryConstructor != null) {
continue;
}
// 判断有没有加@Value或者@Autowired注解,有的话拿到注解值
AnnotationAttributes ann = findAutowiredAnnotation(candidate);
if (ann == null) {
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...
}
}
}
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);
}
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.isWarnEnabled()) {
logger.warn("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 {
candidateConstructors = new Constructor<?>[0];
}
//存放已经被推断完成的类和该类被推断出来的构造方法的集合map
this.candidateConstructorsCache.put(beanClass, candidateConstructors);
}
}
}
return (candidateConstructors.length > 0 ? candidateConstructors : null);
}
public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
@Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {
//实例一个BeanWrapperImpl 对象很好理解
//前面外部返回的BeanWrapper 其实就是这个BeanWrapperImpl
//因为BeanWrapper是个接口
BeanWrapperImpl bw = new BeanWrapperImpl();
this.beanFactory.initBeanWrapper(bw);
// constructorToUse这个对象决定以后用哪个构造方法实例化对象,先定义出来
Constructor<?> constructorToUse = null;
/**
* 构造方法的值,注意不是参数
* 构造方法通过反射来实例化一个对象,在调用反射来实例化的时候,
* 需要具体的值,这个变量就是用来记录这些值的,
* 这里需要注意的是argsHolderToUse是一个数据结构
* argsToUse[]才是真正的值,可以存带索引和不带索引
*/
ArgumentsHolder argsHolderToUse = null;
//确定参数值列表
//argsToUse可以有两种办法设置
//第一种通过beanDefinition设置
//第二种通过xml设置
Object[] argsToUse = null;
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) {
argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);
}
}
if (constructorToUse == null) {
// chosenCtors外面传过来
//如果外面推断出来了,那我在这基础上再次推断,
//没有推断出来等于null,反射获取所有构造方法
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.
//判断构造方法是否为空,多个@Autowired(required = false)时不为null,
// 和判断是否根据构造方法自动注入
boolean autowiring = (chosenCtors != null ||
mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
ConstructorArgumentValues resolvedValues = null;
//定义了最小参数个数
//如果你给构造方法的参数列表给定了具体的值
//那么这些值得个数就是构造方法参数的个数
int minNrOfArgs;
if (explicitArgs != null) {
minNrOfArgs = explicitArgs.length;
}
else {
/**
* MyBatis中@MapperScan,设置构造方法的参数
* implements BeanFactoryPostProcessor
* (GenericBeanDefinition)mbd 强转
* mbd.getConstructorArgumentValues().addGenericArgumentValue("com.index.dao");
*/
//实例一个对象,用来存放构造方法的参数值
//当中主要存放了参数值和参数值所对应的下表
ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
resolvedValues = new ConstructorArgumentValues();
/**
* 确定构造方法参数数量,假设有如下配置:
* <bean id="luban" class="com.luban.Luban">
* <constructor-arg index="0" value="str1"/>
* <constructor-arg index="1" value="1"/>
* <constructor-arg index="2" value="str2"/>
* </bean>
*
* 在通过spring内部给了一个值的情况,那么表示你的构造方法的最小参数个数一定
*
* minNrOfArgs = 3
*/
minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
}
//根据构造方法的访问权限级别和参数数量进行排序
//怎么排序的呢?
/**
* 有访问权限的排前面,public > protected > private
* 然后是 参数个数,参数多的排前面
*
* 这个自己可以写个测试去看看到底是不是和我说的一样
* 1. public Luban(Object o1, Object o2, Object o3)
* 2. public Luban(Object o1, Object o2)
* 3. public Luban(Object o1)
* 4. protected Luban(Integer i, Object o1, Object o2, Object o3)
* 5. protected Luban(Integer i, Object o1, Object o2)
* 6. protected Luban(Integer i, Object o1)
*/
AutowireUtils.sortConstructors(candidates);
/**
* 定义了一个差异变量,这个变量很有分量,后面有解释
*/
int minTypeDiffWeight = Integer.MAX_VALUE;
// 有歧义模糊不清的构造方法,比如差异值算出来一样
Set<Constructor<?>> ambiguousConstructors = null;
LinkedList<UnsatisfiedDependencyException> causes = null;
//循环所有的构造方法
for (Constructor<?> candidate : candidates) {
Class<?>[] paramTypes = candidate.getParameterTypes();
/**
* 这个判断别看只有一行代码理解起来很费劲
* 首先constructorToUse != null这个很好理解,e
* 前面已经说过首先constructorToUse主要是用来装 已经解析过了并且在使用的构造方法
* 只有在他等于空的情况下,才有继续的意义,因为下面如果解析到了一个符合的构造方法
* 就会赋值给这个变量(下面注释有写)。故而如果这个变量不等于null就不需要再进行解析了,
* 说明spring已经找到一个合适的构造方法,直接使用便可以
*
* argsToUse.length > paramTypes.length这个代码就相当复杂了
* 首先假设 argsToUse = [1,"luban",obj]
* 那么回去匹配到上面的构造方法的1和5
* 由于构造方法1有更高的访问权限,所有选择1,尽管5看起来更加匹配
* 但是我们看2,直接参数个数就不对所以直接忽略
*/
if (constructorToUse != 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 {
//判断是否加了ConstructorProperties注解如果加了则把值取出来
//可以写个代码测试一下
//@ConstructorProperties(value = {"xxx", "111"})
String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, paramTypes.length);
if (paramNames == null) {
ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
if (pnd != null) {
//获取构造方法参数名称列表
/**
* 假设你有一个(String luban,Object zilu)
* 则paramNames=[luban,zilu]
*/
paramNames = pnd.getParameterNames(candidate);
}
}
//获取构造方法参数值列表
/**
* 这个方法比较复杂
* 因为spring只能提供字符串的参数值
* 故而需要进行转换
* argsHolder所包含的值就是转换之后的
*
* eg:1>、在这是把获取到的参数字符串转换成对象
* 2>、xml当中配置的ref="xxx",xxx是一个字符串,在这个方法中转换成对象
*/
argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
getUserDeclaredConstructor(candidate), autowiring);
}
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);
}
/**
* typeDiffWeight 差异量,何谓差异量呢?
* argsHolder.arguments和paramTypes之间的差异
* 每个参数值的类型与构造方法参数列表的类型之间的差异
* 通过这个差异量来衡量或者确定一个合适的构造方法
*
* 值得注意的是constructorToUse=candidate
*
* 第一次循环一定会typeDiffWeight < minTypeDiffWeight,因为minTypeDiffWeight的值非常大
* 然后每次循环会把typeDiffWeight赋值给minTypeDiffWeight(minTypeDiffWeight = typeDiffWeight)
* else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight)
* 第一次循环肯定不会进入这个
* 第二次如果进入了这个分支代表什么?
* 代表有两个构造方法都符合我们要求?那么spring有些迷茫了(spring经常在迷茫)
* spring迷茫了怎么办?
* ambiguousConstructors.add(candidate);
* 顾名思义。。。。
* ambiguousConstructors=null 非常重要?
* 为什么重要,因为需要清空
* 这也解释了为什么他找到两个符合要求的方法不直接抛异常的原因
* 如果这个ambiguousConstructors一直存在,spring会在循环外面去exception
* 很牛逼呀!!!!
*/
// 最小编辑距离算法
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) {
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)");
}
/**
* ambiguousConstructors存模糊不清的,
* 然后看是否宽松,bd中可以set,默认宽松,不宽松报异常,
* if (typeDiffWeight < minTypeDiffWeight) {
* constructorToUse = candidate;
* }
* 前面第一遍循环记录到constructorToUse,第二遍存ambiguousConstructors
* 最后采用前面第一遍循环记录到constructorToUse,
* argsHolderToUse.storeCache(mbd, constructorToUse);
*/
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) {
/*
* 缓存相关信息,比如:
* 1. 已解析出的构造方法对象 resolvedConstructorOrFactoryMethod
* 2. 构造方法参数列表是否已解析标志 constructorArgumentsResolved
* 3. 参数值列表 resolvedConstructorArguments 或 preparedConstructorArguments
* 这些信息可用在其他地方,用于进行快捷判断
*/
argsHolderToUse.storeCache(mbd, constructorToUse);
}
}
try {
/*
* 使用反射创建实例 lookup-method 通过CGLIB增强bean实例
*/
final InstantiationStrategy strategy = beanFactory.getInstantiationStrategy();
Object beanInstance;
if (System.getSecurityManager() != null) {
final Constructor<?> ctorToUse = constructorToUse;
final Object[] argumentsToUse = argsToUse;
beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
strategy.instantiate(mbd, beanName, beanFactory, ctorToUse, argumentsToUse),
beanFactory.getAccessControlContext());
}
else {
beanInstance = strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
}
bw.setBeanInstance(beanInstance);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean instantiation via constructor failed", ex);
}
}
3、AbstractAutowireCapableBeanFactory 类中 580 行左右
MergedBeanDefinitionPostProcessor # postProcessMergedBeanDefinition
缓存注解信息,把需要自动注入的信息找出来,放到缓存中,后面自动注入的时候会从缓存中拿。
4、AbstractAutowireCapableBeanFactory 类中 605 行左右
SmartInstantiationAwareBeanPostProcessor # getEarlyBeanReference
得到一个提前暴露的对象,对象不是bean(对象要经过完整的Spring生命周期之后才被称为Bean)。这个方法中解决循环依赖。
5、AbstractAutowireCapableBeanFactory 类中 612 行左右
InstantiationAwareBeanPostProcessor # postProcessAfterInstantiation
判断你的bean需不需要完成属性填充,false不填充。
6、AbstractAutowireCapableBeanFactory 类中 612 行左右
InstantiationAwareBeanPostProcessor # postProcessPropertyValues
这个方法中解决属性填充---自动注入
BeanPostProcessor----Bean初始化过程
当Bean已经new出来并且完成了属性填充(自动装配)
7、AbstractAutowireCapableBeanFactory 类中 614 行左右
BeanPostProcessor # postProcessBeforeInitialization
8、AbstractAutowireCapableBeanFactory 类中 614 行左右
BeanPostProcessor # postProcessAfterInitialization
9、AbstractAutowireCapableBeanFactory 类中 664 行左右
关闭容器Bean销毁时调用这个后置处理器
最后用几张图总结一下:
-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------
不方便用手机看所以拆分了,完整的总结图在这: