6、创建bean
回顾createBean()方法中的内容:
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
//1.锁定class,根据class属性或者根据className来解析Class
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// 验证及准备覆盖的方法
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex);
}
try {
// 给BeanPostProcessors一个机会来返回代理,并用代理替代真正的实例
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,"BeanPostProcessor before instantiation of bean failed", ex);
}
// 创建bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
逻辑分析:
当经过resolveBeforeInstantiation方法后,程序有两个选择,如果创建了代理或者说重写了
InstantitionAwareBeanPostProcessor的postProcessBeforeInstantiation方法并在方法
postProcessBeforeInstantiation中改变了bean, 则直接返回就可以了, 否则需要进行常规bean的创建, 而常规bean创建就是在doCreateBean中完成的
//public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
//实例化bean
BeanWrapper instanceWrapper = null;
//1.如果是单例,则需要将该bean从未完成的FactoryBean实例的缓存中移除
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
//2.实例化bean,将BeanDefinition转换为BeanWrapper
if (instanceWrapper == null) {
//根据指定bean使用对应的策略创建新的实例,如:工厂方法,构造函数自动注入,简单初始化
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
//允许后处理器修改合并的bean定义
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
//3.应用MergedBeanDefinitionPostProcessors
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
mbd.postProcessed = true;
}
}
//4.依赖处理 <注意:必须在进行属性注入之前进行循环依赖处理,因为在属性注入时会检测到依赖bean> <---注意!-----
/**
* 是否需要提早曝光:单例&允许循环依赖&当前bean正在创建中,检测循环依赖
* isSingletonCurrentlyInCreation(beanName):当该bean开始创建时将该beanName放入singletonsCurrentlyInCreation中,说明该bean正在创建
* 只有正在创建的bean才需要解决循环依赖
*/
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
//为避免后期循环依赖,可以在bean初始化完成前将创建实例的ObjectFactory加入工厂
addSingletonFactory(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
//对bean再一次依赖引用,主要应用于SmartInstantiationAware BeanPostProcessor,
//其中我们熟知的AOP就是在这里将advice动态织入bean中,若没有则直接返回bean,不做任何处理
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}
//5.属性填充
Object exposedObject = bean;
try {
//对bean进行填充.将各个属性值注入,其中,可能存在依赖于其他bean的属性,则会递归初始化bean
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
//调用初始化方法,比如init-method
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
//检测循环依赖是否已被解决
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
//earlySingletonReference只有在检测到有循环依赖的情况下才不会为空
if (earlySingletonReference != null) {
//如果exposedObject没有在初始化方法中被改变,也就没有被增强
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
//6.循环依赖检测
for (String dependentBean : dependentBeans) {
//检测依赖
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
/**
* 因为bean创建后其所依赖的bean一定是已经创建的
* actualDependentBeans不为空则表示当前bean创建后其依赖的bean却没有没被全部创建完,也就是说存在循环依赖
*/
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
//7.注册DisposableBean
try {
//根据scope注册bean
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
逻辑分析:
(1) 如果是单例则需要首先清除缓存
(2) 实例化bean,将BeanDefinition装换为BeanWrapper
- 如果存在工程方法则使用工厂方法进行初始化
- 一个类有多个构造函数, 每个构造函数都有不同的参数, 所以需要根据参数锁定构造函数并进行初始化
- 如果既不存在工厂方法也不存在带有参数的构造函数,则使用默认的构造函数进行bean的实例化
(3) MergedBeanDefinitionPostProcessor的应用
bean合并后的处理, Autowired的注解正是通过此方法实现诸如类型的预解析
(4) 依赖处理
在Spring中会有循环依赖的情况, 例如, 当A中含有B的属性, 而B中又含有A的属性时就会构成循环依赖; 此时如果A和B都是单例, 那么在Spring中的处理方式就是当创建B的时候,涉及自动注入A的步骤时, 并不是直接去创建A, 而是通过放入缓存中的ObjectFactory来创建实例, 这样就解决了循环依赖的问题;
(5) 循环依赖检查
在spring中解决循环依赖只对单例有效, 而对prototype的bean, 唯一要做的就是抛出异常; 在这个步骤里面会检测已经加载的bean是否已经出现了循环依赖, 并判断是否需要抛出异常
(7) 注册DisposableBean
如果配置了destory-method, 这里需要注册以便于在销毁时调用
(8) 完成创建并返回
6.1 创建bean的实例
instanceWrapper = createBeanInstance(beanName, mbd, args)
createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) 方法的实现:
//public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactor
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
//解析class
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());
}
//1.如果工厂方法不为空,则使用工厂方法初始化策略
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);
}
}
//需要根据参数解析构造函数
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
//构造函数自动注入
return autowireConstructor(beanName, mbd, ctors, args);
}
//使用默认构造函数构造
return instantiateBean(beanName, mbd);
}
逻辑分析:
(1) 如果在RootBeanDefinition中存在factoryMethodName属性, 或者说在配置文件中配置了factory-method, 那么Spring会尝试使用instantiateUsingFactoryMethod(beanName, mbd, args)方法, 根据RootBeanDefinition中配置生成bean的实例
(2) 解析构造函数并进行构造函数的实例化, 因为一个bean对应的类中可能会有多个构造函数, 而每个构造函数的参数不同,spring再根据参数及类型去判断最终会使用哪个构造函数进行实例化; 但是, 判断的过程是个比较消耗性能的步骤,所以采用缓存机制, 如果已经解析过,则不需要重复解析,而是直接从RootBeanDefinition中的属性resolveConstructorOrFactory
Method缓存的值去取, 否则需要再次解析, 并将解析结果添加至RootBeanDefinition中的属性resolveConstructorOrFactoryMethod中
6.1.1 构造函数自动注入
autowireConstructor(String beanName, RootBeanDefinition mbd, Constructor<?>[] ctors, Object[] explicitArgs)方法的实现:
//public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory
protected BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd, Constructor<?>[] ctors, Object[] explicitArgs) {
return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
}
//class ConstructorResolver
public BeanWrapper autowireConstructor(final String beanName, final RootBeanDefinition mbd, Constructor<?>[] chosenCtors, final Object[] explicitArgs) {
BeanWrapperImpl bw = new BeanWrapperImpl();
this.beanFactory.initBeanWrapper(bw);
Constructor<?> constructorToUse = null;
ArgumentsHolder argsHolderToUse = null;
Object[] argsToUse = null;
//explicitArgs通过getBean方法传入
//如果getBean方法调用的时候是定方法参数那么直接使用
if (explicitArgs != null) {
argsToUse = explicitArgs;
}else {
Object[] argsToResolve = null;
synchronized (mbd.constructorArgumentLock) {
//尝试从缓存中获取构造函数
constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
if (constructorToUse != null && mbd.constructorArgumentsResolved) {
//尝试从缓存中获取参数
argsToUse = mbd.resolvedConstructorArguments;
if (argsToUse == null) {
//配置的构造函数参数
argsToResolve = mbd.preparedConstructorArguments;
}
}
}
//如果缓存中存在
if (argsToResolve != null) {
//解析参数类型,如给定方法的构造函数A(int,int)则通过此方法后就会把配置中的("1","1")转换成(1,1)
//缓存中的值可能是原始值也可能是最终值
argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve);
}
}
//构造函数没有被缓存,则从通过参数来确定可用的构造函数;如果已从缓存中获取,那么可以直接使用创建bean
if (constructorToUse == null) {
//需要解析构造函数
boolean autowiring = (chosenCtors != null || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
ConstructorArgumentValues resolvedValues = null;
int minNrOfArgs;
if (explicitArgs != null) {
minNrOfArgs = explicitArgs.length;
}else {
//提取配置文件中配置的构造函数的参数
ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
//用于承载解析后的构造函数参数的值
resolvedValues = new ConstructorArgumentValues();
//能解析到的参数个数,并且把解析到参数的值存入resolvedValues中
//如果为无参构造函数,则resolvedValues为空,后面根据resolvedValues是否为空,来区分调用无参和有参构造函数
minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
}
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);
}
}
//排序给定的构造函数,public构造函数优先参数数量降序排列,非public构造函数参数数量降序排列
AutowireUtils.sortConstructors(candidates);
int minTypeDiffWeight = Integer.MAX_VALUE;
Set<Constructor<?>> ambiguousConstructors = null;
LinkedList<UnsatisfiedDependencyException> causes = null;
for (int i = 0; i < candidates.length; i++) {
Constructor<?> candidate = candidates[i];
Class<?>[] paramTypes = candidate.getParameterTypes();
if (constructorToUse != null && argsToUse.length > paramTypes.length) {
//如果已经找到选用的构造函数或者需要的参数个数小于当前的构造函数参数个数则终止,因为已经按照参数个数降序排列
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, candidate, autowiring);
}
catch (UnsatisfiedDependencyException ex) {
if (this.beanFactory.logger.isTraceEnabled()) {
this.beanFactory.logger.trace(
"Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
}
// Swallow and try next constructor.
if (causes == null) {
causes = new LinkedList<UnsatisfiedDependencyException>();
}
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));
//如果它代表着当前最接近的匹配,则选择作为构造函数
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<Constructor<?>>();
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.storeCache(mbd, constructorToUse);
}
}
//通过构造函数和相应参数创建bean实例
try {
Object beanInstance;
//安全验证
if (System.getSecurityManager() != null) {
final Constructor<?> ctorToUse = constructorToUse;
final Object[] argumentsToUse = argsToUse;
beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
return beanFactory.getInstantiationStrategy().instantiate(
mbd, beanName, beanFactory, ctorToUse, argumentsToUse);
}
}, beanFactory.getAccessControlContext());
}
//没有安全验证
else {
beanInstance = this.beanFactory.getInstantiationStrategy().instantiate(
mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
}
//将构建的实例加入BeanWrapper中
bw.setWrappedInstance(beanInstance);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean instantiation via constructor failed", ex);
}
}
逻辑分析:
(1) 构造函数参数的确定
- 根据explicitArgs参数确定
如果传入的参数explicitArgs不为空,那便可以直接确定参数,因为explicitArgs参数是在调用bean的时候用户指定的; 在获取bean的时候, 用户不但可以指定bean的名称还可以指定bean所对应的构造函数或者工厂方法的参数, 主要用于静态工厂方法的调用, 而这里是需要给定完全匹配的参数的, 所以, 便可以判断, 如果传入参数explicitArgs不为空, 则可以确定构造函数参数就是它 - 缓存中获取
如果构造函数参数已经记录在缓存中,那么便可以直接拿来使用; 而且, 这里要提到的是, 在缓存中缓存的可能是参数的最终类型也可能是参数的初始类型, 需要经过类型转换器的过滤以确保参数类型与对应的构造参数类型完全对应 - 配置文件获取
如果不能根据传入参数explicitArgs确定构造函数的参数也无法在缓存中获取,那么只能通过配置文件的配置进行获取; spring中配置我呢间中的信息经过转换都会通过BeanDefinition实例承载, 那么可以通过调用mbd.getConstructorArgumentValues()来获取配置的构造函数信息; 有了配置中的信息便可以获取对应的参数值信息了, 获取参数值得信息包括直接指定值,如: 直接指定构造函数中某个值为原始类型String类型, 或者是一个对其他bean的引用,而这已处理委托给resolveConstructorArguments方法, 并返回能解析到的参数的个数
(2)构造函数的确定
经过了第一步后已经确定了构造函数的参数,接下来就是根据构造函数参数在所有的构造函数中锁定对应的构造函数,而匹配的方法就是根据构造参数个数匹配, 所以在匹配之前需要先对构造函数进行排序, 以便在遍历的情况下迅速判断排在后面的构造函数参数个数是否符合条件
由于配置文件中支持两种方式设置构造函数参数,一种是通过参数位置引索的方式去创建,另一种是指定参数名称进行设定参数值得情况, 如<constructor-arg name=“aa”>, 那么这种情况就需要首先确定构造函数中参数名称; 获取参数名称的方式有两种,一种是通过注解的方式直接获取, 另一种就是使用spring中提供的工具类ParameterNameDiscoverer来获取,构造函数、参数名称、参数类型、参数值都确定后就可以根据构造函数以及转换对应的参数类型
(3)根据确定的构造函数转换对应的参数类型
主要是使用spring中提供的类型装换器或者用户提供的自定义类型装换器进行装换
(4) 构造函数不确定性的验证
有时候即使构造函数、参数名称、参数类型、参数值都确定后也不一定会直接锁定构造函数, 不同的构造函数的参数为父子关系,所以spring在最后又做了一次验证
(5) 根据实例化策略以及得到的构造函数及构造函数参数实例化bean
6.1.2 默认构造函数注入
instantiateBean(final String beanName, final RootBeanDefinition mbd)方法的实现:
//public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this;
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
//调用实例化策略
return getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
}, getAccessControlContext());
}
else {
//调用实例化策略
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}
逻辑分析:
无参构造函数中直接调用实例化策略进行实例化就可以了
6.1.3 实例化策略
instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner)方法的实现:
//public class SimpleInstantiationStrategy implements InstantiationStrategy
public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
//如果有需要覆盖或者动态替换的方法则需要使用cglib进行动态代理,因为可以在创建代理的同时将动态方法织入类中
//但是如果没有需要动态改变方法,为了方便直接反射就可以了
if (bd.getMethodOverrides().isEmpty()) {
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(new PrivilegedExceptionAction<Constructor<?>>() {
@Override
public Constructor<?> run() throws Exception {
return clazz.getDeclaredConstructor((Class[]) null);
}
});
}
else {
constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
}
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Exception ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// Must generate CGLIB subclass.
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
6.2、依赖处理(记录创建bean的ObjectFactory)
//4.依赖处理 <注意:必须在进行属性注入之前进行循环依赖处理,因为在属性注入时会检测到依赖bean> <---注意!-----
/**
* 是否需要提早曝光:单例&允许循环依赖&当前bean正在创建中
* isSingletonCurrentlyInCreation(beanName):当该bean开始创建时将该beanName放入singletonsCurrentlyInCreation中,说明该bean正在创建
* 只有正在创建的bean才需要解决循环依赖
*/
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
//为避免后期循环依赖,可以在bean初始化完成前将创建实例的ObjectFactory加入工厂
addSingletonFactory(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
//对bean再一次依赖引用,主要应用于SmartInstantiationAware BeanPostProcessor,
//其中我们熟知的AOP就是在这里将advice动态织入bean中,若没有则直接返回bean,不做任何处理
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}
逻辑分析:
通过构造函数将bean进行初始化后, 判断是否需要进行依赖处理; 是否需要提早曝光必须满足这三个条件: 单例&允许循环依赖&当前bean正在创建中 满足提前曝光的条件的话需要将创建bean的ObjectFactory加入singletonFactories缓存中; 在接下来的属性填充中会出向循环依赖, 在获取依赖bean是会首先尝试从缓存中获取依赖的bean,以达到循环依赖解决
6.3、属性注入
populateBean(beanName, mbd, instanceWrapper)
populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) 方法的实现:
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
//获取bean的属性名和值
PropertyValues pvs = mbd.getPropertyValues();
if (bw == null) {
if (!pvs.isEmpty()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
//没有可填充的属性,直接返回
return;
}
}
// 应用后处理器InstantiationAwareBeanPostProcessor,调用其postProcessAfterInstantiation方法
// 在注入属性前修改bean状态,如果方法中返回false的话,可以终止后面代码运行,直接返回
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//返回值为是否继续填充bean
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
//如果后处理器发出停止填充命令,则终止后续的执行
if (!continueWithPropertyPopulation) {
return;
}
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
//根据名称自动注入
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
//根据类型自动注入
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
//后处理器已经初始化
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
//需要依赖检查
boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
if (hasInstAwareBpps || needsDepCheck) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//对所有需要依赖检查的属性进行后处理
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
//依赖检查,对应depends-on属性,3.0已经弃用此属性
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
//将属性应用到bean中
applyPropertyValues(beanName, mbd, bw, pvs);
}
逻辑分析:
(1) InstantiationAwareBeanPostProcessor处理器的postProcessAfterInstantiation方法的应用,此方法可以控制程序是否继续进行属性填充
(2) 根据注入类型(byName/byType),提取依赖的bean, 并统一存入PropertyValues中
(3) 应用InstantiationAwareBeanPostProcessor处理器的postProcessAfterInstantiation方法,对属性获取完毕填充前对属性的再次处理, 典型应用是RequiredAnnotationBeanPostPr
ocessor类中对属性的验证
(4) 将所有PropertyValues中的属性填充至BeanWrapper中
6.3.1 根据名称注入
protected void autowireByName(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
//寻找bw中需要依赖注入的属性(找到Bean中属性是对象类型的属性)
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
if (containsBean(propertyName)) {
//递归初始化相关的bean
Object bean = getBean(propertyName);
pvs.add(propertyName, bean);
//注册依赖bean
registerDependentBean(propertyName, beanName);
//日志记录
if (logger.isDebugEnabled()) {
logger.debug("Added autowiring by name from bean name '" + beanName +
"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
}
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
"' by name: no matching bean found");
}
}
}
}
逻辑分析:
(1)查询出需要依赖注入的属性
(2) 遍历需要依赖注入的属性,递归初始化相关的bean
(3) 将依赖的beanName和初始化得到的bean加入到MutablePropertyValues类型实例中
(4) 注册依赖的bean
6.3.2 根据类型注入
protected void autowireByType(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
Set<String> autowiredBeanNames = new LinkedHashSet<String>(4);
//寻找bw中需要依赖注入的属性名称(找到Bean中属性是对象类型的属性)
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
try {
//根据属性名称获取属性描述信息
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
if (Object.class != pd.getPropertyType()) {
//探测到指定属性的set方法
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// Do not allow eager init for type matching in case of a prioritized post-processor.
boolean eager = !PriorityOrdered.class.isAssignableFrom(bw.getWrappedClass());
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
//解析指定beanName的属性所匹配的值,并把解析到的属性名称存储在autoWiredBeanName中,当属性存在多个封装bean时,如:
//@Autowired
//private List<A> aList;将会找到所有匹配A类型的bean并将其注入;autowiredArgument的类型可能是集合,数组,对象等
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
//将属性名和属性值添加到MutablePropertyValues中
if (autowiredArgument != null) {
pvs.add(propertyName, autowiredArgument);
}
for (String autowiredBeanName : autowiredBeanNames) {
//注册依赖
registerDependentBean(autowiredBeanName, beanName);
if (logger.isDebugEnabled()) {
logger.debug("Autowiring by type from bean name '" + beanName + "' via property '" +
propertyName + "' to bean named '" + autowiredBeanName + "'");
}
}
autowiredBeanNames.clear();
}
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
}
}
}
逻辑分析:
(1)查询出需要依赖注入的属性
(2) 遍历需要依赖注入的属性寻找类型匹配的的bean,对bean进行注入,同时spring中提供了对集合类型注入的支持,对于寻找类型匹配的逻辑实现封装在了resolveDependency方法中
(3) 将依赖的属性名称和匹配到的bean加入到MutablePropertyValues类型实例中
(4) 注册依赖的bean
6.3.3 将注入的属性应用到实例化的bean中
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
if (pvs == null || pvs.isEmpty()) {
return;
}
MutablePropertyValues mpvs = null;
List<PropertyValue> original;
if (System.getSecurityManager() != null) {
if (bw instanceof BeanWrapperImpl) {
((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
}
}
if (pvs instanceof MutablePropertyValues) {
mpvs = (MutablePropertyValues) pvs;
//如果mpvs中的值已经被转换为对应的类型那么可以直接设置到beanwrapper中
if (mpvs.isConverted()) {
// Shortcut: use the pre-converted values as-is.
try {
bw.setPropertyValues(mpvs);
return;
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
original = mpvs.getPropertyValueList();
}
else {
original = Arrays.asList(pvs.getPropertyValues());
}
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
//获取对应的解析器
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
// Create a deep copy, resolving any references for values.
List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size());
boolean resolveNecessary = false;
//遍历属性,将属性转换为对应类的对应属性的类型
for (PropertyValue pv : original) {
if (pv.isConverted()) {
deepCopy.add(pv);
}
else {
String propertyName = pv.getName();
Object originalValue = pv.getValue();
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
Object convertedValue = resolvedValue;
boolean convertible = bw.isWritableProperty(propertyName) &&
!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
if (convertible) {
convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
}
// Possibly store converted value in merged bean definition,
// in order to avoid re-conversion for every created bean instance.
if (resolvedValue == originalValue) {
if (convertible) {
pv.setConvertedValue(convertedValue);
}
deepCopy.add(pv);
}
else if (convertible && originalValue instanceof TypedStringValue &&
!((TypedStringValue) originalValue).isDynamic() &&
!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
pv.setConvertedValue(convertedValue);
deepCopy.add(pv);
}
else {
resolveNecessary = true;
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
}
if (mpvs != null && !resolveNecessary) {
mpvs.setConverted();
}
// Set our (possibly massaged) deep copy.
try {
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
逻辑分析:
到这里已经完成对所有注入属性的获取, 但获取的属性是以PropertyValues形式存在的,所以还需要应用到已经实例化的bean中
6.4 初始化bean
exposedObject = initializeBean(beanName, exposedObject, mbd)
initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd)方法的实现:
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}
else {
//对特殊的bean处理:Aware,BeanClassLoaderAware,BeanFactoryAware
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//应用后处理器
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//激活用户自定义的init方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
//后处理器应用
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
逻辑分析:
(1) 激活Aware方法
(2) 处理器的应用
(3) 激活自定义的init方法
6.4.1 激活Aware方法(对特殊的bean处理)
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
6.4.2 处理器的应用(重点)
(1) BeanPostProcessor的使用位置就是这里, 在调用自定义初始化方法前后分别会获取所有已注册的BeanPostProcessor, 然后遍历每一个BeanPostProcessor, 并调用其中的applyBeanPostProcessorsBeforeInitialization, applyBeanPostProcessorsAfterInitialization方法;
(2) 用户可以通过继承BeanPostProcessor接口, 重写postProcessBeforeInitialization和postProcessAfterInitialization方法对每一个bean进行修改,或者根据传入的beanName针对指定bean进行处理;
(3) Spring容器通过BeanPostProcessor给了我们一个机会对Spring管理的bean进行再加工。比如:我们可以修改bean的属性,可以给bean生成一个动态代理实例等等。一些Spring AOP的底层处理也是通过实现BeanPostProcessor来执行代理包装逻辑的。
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
invokeInitMethods(beanName, wrappedBean, mbd);
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName)方法的实现:
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
//获取所有已注册的BeanPostProcessor,遍历执行每一个BeanPostProcessor中重写的postProcessBeforeInitialization方法
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName)方法的实现:
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
//获取所有已注册的BeanPostProcessor,遍历执行每一个BeanPostProcessor中重写的postProcessAfterInitialization方法
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessAfterInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
6.4.3 激活自定义的init方法
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
//首先检查是否是InitializingBean,如果是的话需要调用afterPropertiesSet方法
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
((InitializingBean) bean).afterPropertiesSet();
return null;
}
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
//属性初始化后的梳理
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null) {
String initMethodName = mbd.getInitMethodName();
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
//调用自定义初始化方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
6.5 注册DisposableBean
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
if (mbd.isSingleton()) {
/**
* 单例模式下注册需要销毁的bean,此方法会处理实现DisposableBean的bean,
* 并且对所有的bean使用DestructionAwareBeanPostProcessors处理
* DisposableBean DestructionAwareBeanProcessors,
*/
registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
else {
/**
* 自定义scope的处理
*/
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
}
scope.registerDestructionCallback(beanName, new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
}
}
逻辑分析:
spring中不但提供了对于初始化方法的扩展入口同样与提供了销毁方法的扩展入口, 对于销毁方法的扩展,除了配置属性destory-method外,用户还可以注册后处理器DestructionAware
BeanPostProcessor来统一处理bean的销毁方法