参考:
//www.greatytc.com/p/6f7a82d869e7
Spring中解析注册过程
1、使用Resource定位xml配置
2、使用BeanDefinitionReader读取配置,并封装成BeanDefinition
3、使用BeanDefinitionRegistry将BeanDefinition注册到BeanDefinitionMap中
Spring中BeanFactory加载bean的过程
// AbstractBeanFactory中方法
public Object getBean(String name) throws BeansException {
return this.doGetBean(name, (Class)null, (Object[])null, false);
}
protected <T> T doGetBean(String name, Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException {
// 转换对应的beanName:传入的参数可能不是bean的name,可能是别名、FactoryBean(&开头)
final String beanName = this.transformedBeanName(name);
/**
* 如果是单例,尝试从缓存中获取单例bean,
* 获取失败再尝试从singletonFactories中获取单例工厂,通过单例工厂去加载
* (在创建单例bean时为解决依赖注入,不等bean创建完成就将创建bean的工厂提早曝光并加入缓存中,
* 其他单例bean创建时如果需要依赖该bean,直接从缓存中获取或获取工厂去创建)
*/
Object sharedInstance = this.getSingleton(beanName);
Object bean;
if (sharedInstance != null && args == null) {
// 如果是单例bean且已经存在
if (this.logger.isDebugEnabled()) {
if (this.isSingletonCurrentlyInCreation(beanName)) {
this.logger.debug("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet - a consequence of a circular reference");
} else {
this.logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
// 返回对应的单例bean:获取的bean可能是原始状态(有可能获取的是FactoryBean,需要调用FactoryBean中的getObject方法转换bean)
bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, (RootBeanDefinition)null);
} else {
// 如果没有获取到单例bean
if (this.isPrototypeCurrentlyInCreation(beanName)) {
// 如果是原型模式bean,如果存在循环依赖,则直接抛出异常
throw new BeanCurrentlyInCreationException(beanName);
}
// 获取parentBeanFactory
BeanFactory parentBeanFactory = this.getParentBeanFactory();
if (parentBeanFactory != null && !this.containsBeanDefinition(beanName)) {
// 根据beanName尝试从beanDefinitionMap中获取对应的beanDefinition中的配置
// 如果获取不到配置,尝试递归根据parentBeanFactory去加载(调用父类工厂的getBean方法)
String nameToLookup = this.originalBeanName(name);
if (args != null) {
return parentBeanFactory.getBean(nameToLookup, args);
}
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
if (!typeCheckOnly) {
this.markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = this.getMergedLocalBeanDefinition(beanName);
this.checkMergedBeanDefinition(mbd, beanName, args);
String[] dependsOn = mbd.getDependsOn();
String[] var11;
// 如果存在依赖则需要先递归创建依赖的bean
if (dependsOn != null) {
var11 = dependsOn;
int var12 = dependsOn.length;
for(int var13 = 0; var13 < var12; ++var13) {
String dep = var11[var13];
if (this.isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
// 注册依赖的bean
this.registerDependentBean(dep, beanName);
this.getBean(dep);
}
}
// 针对不同的scope进行bean的创建(如果单例bean在前面没有获取到,要从头开始创建)
if (mbd.isSingleton()) {
sharedInstance = this.getSingleton(beanName, new ObjectFactory<Object>() {
public Object getObject() throws BeansException {
try {
return AbstractBeanFactory.this.createBean(beanName, mbd, args);
} catch (BeansException var2) {
AbstractBeanFactory.this.destroySingleton(beanName);
throw var2;
}
}
});
bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
} else if (mbd.isPrototype()) {
var11 = null;
Object prototypeInstance;
try {
this.beforePrototypeCreation(beanName);
prototypeInstance = this.createBean(beanName, mbd, args);
} finally {
this.afterPrototypeCreation(beanName);
}
bean = this.getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
} else {
String scopeName = mbd.getScope();
Scope scope = (Scope)this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
public Object getObject() throws BeansException {
AbstractBeanFactory.this.beforePrototypeCreation(beanName);
Object var1;
try {
var1 = AbstractBeanFactory.this.createBean(beanName, mbd, args);
} finally {
AbstractBeanFactory.this.afterPrototypeCreation(beanName);
}
return var1;
}
});
bean = this.getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
} catch (IllegalStateException var21) {
throw new BeanCreationException(beanName, "Scope '" + scopeName + "' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton", var21);
}
}
} catch (BeansException var23) {
this.cleanupAfterBeanCreationFailure(beanName);
throw var23;
}
}
// 类型转换:将bean转换为需要的类型
if (requiredType != null && bean != null && !requiredType.isInstance(bean)) {
try {
return this.getTypeConverter().convertIfNecessary(bean, requiredType);
} catch (TypeMismatchException var22) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", var22);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
} else {
return bean;
}
}
1、转换对应的beanName:传入的参数可能不是bean的name,可能是别名、FactoryBean(&开头)
a、FactoryBean:
一般情况下,Spring通过反射机制来实例化bean,而这样可能需要很多配置,可以通过实现FactoryBean接口以编码的方式来代替
当bean实现FactoryBean接口时,通过工厂的getBean方法返回的是FactoryBean中的getObject方法返回的实例,如果想要返回当前bean,需要以&开头
b、BeanFactory:
2、如果是单例,尝试从缓存中获取单例bean,获取失败再尝试从singletonFactories中获取单例工厂,通过单例工厂去加载(在创建单例bean时为解决依赖注入,不等bean创建完成就将创建bean的工厂提早曝光并加入缓存中,其他单例bean创建时如果需要依赖该bean,直接从缓存中获取或获取工厂去创建)
// DefaultSingletonBeanRegistry中方法
public Object getSingleton(String beanName) {
return this.getSingleton(beanName, true);
}
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// 从单例缓存singletonObjects中获取单例bean
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && this.isSingletonCurrentlyInCreation(beanName)) {
// 如果单例缓存中不存在单例bean 同步处理
synchronized(this.singletonObjects) {
// 如果单例bean已经在创建 则不处理
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
// 如果单例bean还未创建完成 并且 允许提前曝光
// 从单例工厂缓存singletonFactories中获取单例工厂
ObjectFactory<?> singletonFactory = (ObjectFactory)this.singletonFactories.get(beanName);
if (singletonFactory != null) {
// 如果获取到单例工厂 根据单例工厂获取单例bean 实例化了但还未初始化
singletonObject = singletonFactory.getObject();
// 两个缓存互斥:
// 将singletonObject缓存到earlySingletonObjects中
// 这里单例bean还未创建好(实例化了但还未初始化) 但是已经可以根据单例工厂的getBean方法已经可以获取了 为了解决循环依赖
this.earlySingletonObjects.put(beanName, singletonObject);
// 将单例工厂从缓存singletonFactories中移除
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject != NULL_OBJECT ? singletonObject : null;
}
3、返回单例bean的转换:获取的bean可能是原始状态(有可能获取的是Factorybean,需要调用FactoryBean中的getObject方法转换bean)
// AbstractBeanFactory中方法
protected Object getObjectForBeanInstance(Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {
if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(this.transformedBeanName(name), beanInstance.getClass());
} else if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
// 如果返回bean是FactoryBean类型的bean 并且beanName不是以&开头
Object object = null;
if (mbd == null) {
object = this.getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
FactoryBean<?> factory = (FactoryBean)beanInstance;
if (mbd == null && this.containsBeanDefinition(beanName)) {
mbd = this.getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = mbd != null && mbd.isSynthetic();
// 调用FactoryBean的getObject方法获取单例bean
object = this.getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
} else {
return beanInstance;
}
}
// FactoryBeanRegistrySupport中方法
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
if (factory.isSingleton() && this.containsSingleton(beanName)) {
// 同步处理
synchronized(this.getSingletonMutex()) {
Object object = this.factoryBeanObjectCache.get(beanName);
if (object == null) {
object = this.doGetObjectFromFactoryBean(factory, beanName);
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
object = alreadyThere;
} else {
if (object != null && shouldPostProcess) {
try {
// 调用工厂的后处理器
object = this.postProcessObjectFromFactoryBean(object, beanName);
} catch (Throwable var9) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's singleton object failed", var9);
}
}
this.factoryBeanObjectCache.put(beanName, object != null ? object : NULL_OBJECT);
}
}
return object != NULL_OBJECT ? object : null;
}
} else {
Object object = this.doGetObjectFromFactoryBean(factory, beanName);
if (object != null && shouldPostProcess) {
try {
// 调用工厂的后处理器
object = this.postProcessObjectFromFactoryBean(object, beanName);
} catch (Throwable var11) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", var11);
}
}
return object;
}
}
private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, String beanName) throws BeanCreationException {
Object object;
try {
if (System.getSecurityManager() != null) {
AccessControlContext acc = this.getAccessControlContext();
try {
object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
return factory.getObject();
}
}, acc);
} catch (PrivilegedActionException var6) {
throw var6.getException();
}
} else {
// 调用FactoryBean的getObject方法获取单例bean
object = factory.getObject();
}
} catch (FactoryBeanNotInitializedException var7) {
throw new BeanCurrentlyInCreationException(beanName, var7.toString());
} catch (Throwable var8) {
throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", var8);
}
if (object == null && this.isSingletonCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName, "FactoryBean which is currently in creation returned null from getObject");
} else {
return object;
}
}
4、如果是原型模式bean,如果存在循环依赖,则直接抛出异常
5、如果上面没有获取到单例bean,根据beanName尝试从beanDefinitionMap中获取对应的beanDefinition中的配置,如果获取不到配置,尝试递归根据parentBeanFactory去加载(调用父类工厂的getBean方法)
6、如果存在依赖则需要先递归创建依赖的bean
7、针对不同的scope进行bean的创建(如果单例bean在前面没有获取到,要从头开始创建)
单例bean的创建:
// AbstractBeanFactory中方法
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "'beanName' must not be null");
// 同步处理 单例缓存singletonObjects
synchronized(this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
// 如果从单例缓存singletonObjects中获取不到单例bean 才去创建
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName, "Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (this.logger.isDebugEnabled()) {
this.logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
// 创建单例bean之前处理 记录单例bean正在创建状态 用于检测循环依赖
this.beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = this.suppressedExceptions == null;
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet();
}
try {
// 通过单例工厂创建单例bean 单例bean还没创建好
singletonObject = singletonFactory.getObject();
newSingleton = true;
} catch (IllegalStateException var16) {
// 如果初始化失败 尝试从单例缓存singletonObjects中获取
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw var16;
}
} catch (BeanCreationException var17) {
BeanCreationException ex = var17;
if (recordSuppressedExceptions) {
Iterator var8 = this.suppressedExceptions.iterator();
while(var8.hasNext()) {
Exception suppressedException = (Exception)var8.next();
ex.addRelatedCause(suppressedException);
}
}
throw ex;
} finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
// 创建单例bean之后处理 移除单例bean正在创建状态 用于检测循环依赖
this.afterSingletonCreation(beanName);
}
if (newSingleton) {
/**
* 将单例bean放入单例缓存singletonObjects
* 从单例工厂缓存singletonFactories中移除单例工厂
* 从单例bean缓存earlySingletonObjects中移除单例bean
* 保存已注册的单例bean
*/
this.addSingleton(beanName, singletonObject);
}
}
return singletonObject != NULL_OBJECT ? singletonObject : null;
}
}
protected void addSingleton(String beanName, Object singletonObject) {
synchronized(this.singletonObjects) {
// 将单例bean放入单例缓存singletonObjects
this.singletonObjects.put(beanName, singletonObject != null ? singletonObject : NULL_OBJECT);
// 从单例工厂缓存singletonFactories中移除单例工厂
this.singletonFactories.remove(beanName);
// 从单例bean缓存earlySingletonObjects中移除单例bean
this.earlySingletonObjects.remove(beanName);
// 保存已注册的单例bean
this.registeredSingletons.add(beanName);
}
}
a、前置处理:创建单例bean之前,记录单例bean正在创建状态,用于检测循环依赖
b、通过单例工厂创建单例bean,调用单例工厂的getObject方法获取提早曝光的单例bean
// AbstractAutowireCapableBeanFactory中方法
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// 解析class
Class<?> resolvedClass = this.resolveBeanClass(mbd, beanName, new Class[0]);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
try {
// 处理override属性:lookup-method、replace-method存放在beanDefinition的methodOverrides中
mbdToUse.prepareMethodOverrides();
} catch (BeanDefinitionValidationException var7) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", var7);
}
Object beanInstance;
try {
// 实例化单例bean前置处理
beanInstance = this.resolveBeforeInstantiation(beanName, mbdToUse);
// 短路处理:Spring AOP代理实现,如果需要使用代理bean且代理bean已经创建,直接返回
if (beanInstance != null) {
return beanInstance;
}
} catch (Throwable var8) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", var8);
}
// 创建单例bean
beanInstance = this.doCreateBean(beanName, mbdToUse, args);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
处理override属性:为了后面实例化单例bean时更好的处理,这里先预先判断一下是否需要覆盖或重载,后面处理的原理就是在实例化bean时如果检测到methodOverrides时,会动态地为当前bean生成代理并使用对应的拦截器为bean做增强处理
// AbstractBeanDefinition中方法
public void prepareMethodOverrides() throws BeanDefinitionValidationException {
MethodOverrides methodOverrides = this.getMethodOverrides();
if (!methodOverrides.isEmpty()) {
Set<MethodOverride> overrides = methodOverrides.getOverrides();
synchronized(overrides) {
Iterator var4 = overrides.iterator();
while(var4.hasNext()) {
MethodOverride mo = (MethodOverride)var4.next();
this.prepareMethodOverride(mo);
}
}
}
}
protected void prepareMethodOverride(MethodOverride mo) throws BeanDefinitionValidationException {
// 获取对应类中对应方法名的个数
int count = ClassUtils.getMethodCountForName(this.getBeanClass(), mo.getMethodName());
if (count == 0) {
throw new BeanDefinitionValidationException("Invalid method override: no method with name '" + mo.getMethodName() + "' on class [" + this.getBeanClassName() + "]");
} else {
if (count == 1) {
// 如果只有一个重载方法 后面就不需要再处理
mo.setOverloaded(false);
}
}
}
实例化单例bean前置处理:
// AbstractAutowireCapableBeanFactory中方法
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
if (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = this.determineTargetType(beanName, mbd);
if (targetType != null) {
// 实例化单例bean前置处理
bean = this.applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
// 初始化单例bean后置处理
bean = this.applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = bean != null;
}
return bean;
}
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
Iterator var3 = this.getBeanPostProcessors().iterator();
while(var3.hasNext()) {
BeanPostProcessor bp = (BeanPostProcessor)var3.next();
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
Object result = existingBean;
Iterator var4 = this.getBeanPostProcessors().iterator();
do {
if (!var4.hasNext()) {
return result;
}
BeanPostProcessor beanProcessor = (BeanPostProcessor)var4.next();
result = beanProcessor.postProcessAfterInitialization(result, beanName);
} while(result != null);
return result;
}
创建单例bean:需要先移除原来缓存中的单例bean;实例化单例bean(工厂方法或构造函数),即将BeanDefinition转换为BeanWrapper,需要选择不同的实例化策略:如果有需要覆盖或动态替换的方法,需要使用cglib进行动态代理,因为可以在创建代理的同时将动态方法织入类中,否则可以直接用反射;如果需要解决循环依赖(满足3个条件:单例、允许循环依赖、当前bean正在创建),则提早曝光单例工厂(将单例工厂放入工厂缓存singletonFactories中,其他单例bean在创建时调用getObject方法可以获取未创建好的单例bean,getObject方法中实现spring AOP 的advice动态织入);属性注入(填充)(递归初始化);调用初始化方法如init-method;检测循环依赖;注册destroy-method销毁方法
// AbstractAutowireCapableBeanFactory中方法
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// 如果是单例bean需要先移除原来的缓存
instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
/**
* 实例化单例bean 即将beanDefinition转换为beanWrapper:
* 如果有工厂方法 使用工厂方法实例化
* 否则 根据参数匹配构造函数实例化
* 否则 使用默认构造函数实例化
* 注:构造函数注入循环依赖问题spring不能解决 循环依赖是在实例化后处理的(在下面)
*/
instanceWrapper = this.createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null;
Class<?> beanType = instanceWrapper != null ? instanceWrapper.getWrappedClass() : null;
mbd.resolvedTargetType = beanType;
synchronized(mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// 合并bean后的处理(将继承父类的内容合进来) Autowired注解在这里实现类型等的预解析
this.applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
} catch (Throwable var17) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", var17);
}
mbd.postProcessed = true;
}
}
// 如果是单例、允许循环依赖、当前bean正在创建 满足这3个条件 后面才会去解决循环依赖问题
boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
if (earlySingletonExposure) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references");
}
// 提早曝光实例化好的单例bean(还未初始化):将单例工厂放入工厂缓存singletonFactories中
this.addSingletonFactory(beanName, new ObjectFactory<Object>() {
// 其他单例bean在创建时调用getObject方法可以获取单例bean
public Object getObject() throws BeansException {
// spring AOP 在这里将advice动态织入单例bean中
return AbstractAutowireCapableBeanFactory.this.getEarlyBeanReference(beanName, mbd, bean);
}
});
}
Object exposedObject = bean;
try {
// 属性填充:如果属性还依赖于其他bean 则递归初始化bean
this.populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
// 调用初始化方法:如init-method
exposedObject = this.initializeBean(beanName, exposedObject, mbd);
}
} catch (Throwable var18) {
if (var18 instanceof BeanCreationException && beanName.equals(((BeanCreationException)var18).getBeanName())) {
throw (BeanCreationException)var18;
}
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", var18);
}
if (earlySingletonExposure) {
Object earlySingletonReference = this.getSingleton(beanName, false);
// earlySingletonReference只有在检测到循环依赖的时候才不为空
if (earlySingletonReference != null) {
if (exposedObject == bean) {
// 如果exposedObject没有在初始化方法被改变
exposedObject = earlySingletonReference;
} else if (!this.allowRawInjectionDespiteWrapping && this.hasDependentBean(beanName)) {
String[] dependentBeans = this.getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet(dependentBeans.length);
String[] var12 = dependentBeans;
int var13 = dependentBeans.length;
for(int var14 = 0; var14 < var13; ++var14) {
String dependentBean = var12[var14];
// 循环依赖检查
if (!this.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.");
}
}
}
}
try {
// 注册disposableBean:如果配置了destroy-method需要注册
this.registerDisposableBeanIfNecessary(beanName, bean, mbd);
return exposedObject;
} catch (BeanDefinitionValidationException var16) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", var16);
}
}
**调用初始化方法:激活aware方法;初始化单例bean前置处理器 ;激活用户自定义的init方法:如afterPropertiesSet方法、init-method,afterPropertiesSet先执行,init-method后执行;初始化单例bean后置处理器(spring AOP 在这里实现)
// AbstractAutowireCapableBeanFactory中方法
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
AbstractAutowireCapableBeanFactory.this.invokeAwareMethods(beanName, bean);
return null;
}
}, this.getAccessControlContext());
} else {
/**
* 激活aware方法:通过aware方法可以获取对应的资源
* BeanNameAware 获取bean名称
* BeanClassLoaderAware 获取bean的类加载器
* BeanFactory 获取bean的工厂
*/
this.invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 初始化单例bean前置处理器
wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
}
try {
/**
* 激活用户自定义的init方法:如afterPropertiesSet方法、init-method
* afterPropertiesSet先执行 init-method后执行
*/
this.invokeInitMethods(beanName, wrappedBean, mbd);
} catch (Throwable var6) {
throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6);
}
if (mbd == null || !mbd.isSynthetic()) {
// 初始化单例bean后置处理器:spring AOP 在这里实现
wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
c、后置处理:创建单例bean之后,移除单例bean正在创建状态,用于检测循环依赖
d、将单例bean放入单例缓存singletonObjects,从单例工厂缓存singletonFactories中移除单例工厂,从单例bean缓存earlySingletonObjects中移除单例bean,保存已注册的单例bean
8、类型转换:将bean转换为需要的类型
ApplicationContext(企业常用)
ApplicationContext包含BeanFactory所有的功能
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:application.xml");
applicationContext.getBean(BaseController.class);
}
设置配置文件路径,并替换变量
// ClassPathXmlApplicationContext中方法
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[]{configLocation}, true, (ApplicationContext)null);
}
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException {
super(parent);
// 配置文件路径(数组形式 支持多个文件)
this.setConfigLocations(configLocations);
if (refresh) {
this.refresh();
}
}
public void setConfigLocations(String... locations) {
if (locations != null) {
Assert.noNullElements(locations, "Config locations must not be null");
this.configLocations = new String[locations.length];
for(int i = 0; i < locations.length; ++i) {
// 如果配置中含有特殊符号 如${} 在这里会寻找匹配的系统变量进行替换
this.configLocations[i] = this.resolvePath(locations[i]).trim();
}
} else {
this.configLocations = null;
}
}
protected String resolvePath(String path) {
return this.getEnvironment().resolveRequiredPlaceholders(path);
}
扩展功能
// AbstractApplicationContext中方法
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
// 准备刷新时需要的上下文环境及验证:如系统属性或环境变量
this.prepareRefresh();
// 加载beanFactory 并读取配置文件
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
// 对beanFactory进行功能填充:如对@Qualifier、@Autowired注解的支持
this.prepareBeanFactory(beanFactory);
try {
// 子类方法可以覆盖进而做额外处理
this.postProcessBeanFactory(beanFactory);
// 激活beanFactory处理器
this.invokeBeanFactoryPostProcessors(beanFactory);
// 注册 拦截bean创建的bean处理器 在getBean方法中会调用这些处理器
this.registerBeanPostProcessors(beanFactory);
// 国际化处理
this.initMessageSource();
// 初始化要用消息广播器
this.initApplicationEventMulticaster();
// 留给子类覆盖去处理其他的bean
this.onRefresh();
// 注册监听器
this.registerListeners();
// 通过beanFactory初始化bean
this.finishBeanFactoryInitialization(beanFactory);
// 完成刷新过程:通知生命周期管理器lifecycleProcessor刷新过程 提示事件通知监听器
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
// 销毁bean
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
1、环境准备:如系统属性或环境变量的准备及验证
2、加载beanFactory,并读取配置文件:创建beanFactory(DefaultListableBeanFactory);定制beanFactory;加载beanDefinition,读取配置文件;使用全局变量记录beanFactory
// ClassPathXmlApplicationContext中方法
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
this.refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = this.getBeanFactory();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Bean factory for " + this.getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
// AbstractRefreshableApplicationContext中方法
protected final void refreshBeanFactory() throws BeansException {
if (this.hasBeanFactory()) {
this.destroyBeans();
this.closeBeanFactory();
}
try {
// 创建DefaultListableBeanFactory
DefaultListableBeanFactory beanFactory = this.createBeanFactory();
beanFactory.setSerializationId(this.getId());
// 定制beanFactory
this.customizeBeanFactory(beanFactory);
// 加载beanDefinition 读取配置文件
this.loadBeanDefinitions(beanFactory);
synchronized(this.beanFactoryMonitor) {
// 使用全局变量记录beanFactory
this.beanFactory = beanFactory;
}
} catch (IOException var5) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + this.getDisplayName(), var5);
}
}
定制beanFactory:在基本容器的基础上,增加了是否允许覆盖是否允许扩展的设置,并提供了对注解@Qualifier、@Autowired的支持
// AbstractRefreshableApplicationContext中方法
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
// 是否允许覆盖同名称不同定义的对象
if (this.allowBeanDefinitionOverriding != null) {
beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
// 是否允许bean之间存在循环依赖
if (this.allowCircularReferences != null) {
beanFactory.setAllowCircularReferences(this.allowCircularReferences);
}
}
加载beanDefinition,读取配置文件:通过beanDefinitionReader加载beanDefinition(并注册到beanFactory的BeanDefinitionMap中)
// AbstractXmlApplicationContext中方法
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// 创建beanDefinitionReader
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
this.initBeanDefinitionReader(beanDefinitionReader);
// 通过beanDefinitionReader加载beanDefinition
this.loadBeanDefinitions(beanDefinitionReader);
}
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = this.getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = this.getConfigLocations();
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}
3、对BeanFactory进行功能填充:如对@Qualifier和@Autowired注解的支持;增加AspectJ支持;增加属性注册编辑器(Spring DI 依赖注入时 Date类型是无法识别的)
4、子类通过覆盖方法做额外处理
5、激活(调用)beanFactory处理器(容器级),可以有多个,通过排序依次处理;beanFactory处理器可以在实例化任何bean之前获得配置元数据并修改(如${}替换);注册bean处理器(beanFactory没有注册(因此不能使用),需要手动注册),在bean创建时调用
6、注册拦截bean创建的bean处理器,这里只是注册,真正调用是在getBean方法中
7、国际化处理
8、初始化应用消息广播器
9、子类覆盖方法处理
10、在所有注册的bean中查找要监听的bean,注册到消息广播器中(注册监听器,并在合适的时候通知监听器)
11、通过beanFactory加载bean(非延迟加载):ApplicationContext在启动时会加载所有的单例bean,调用getBean方法(上面Spring中BeanFactory加载bean的过程)
12、完成刷新,通知生命周期管理器lifecycleProcessor刷新过程,并通过事件通知监听者
Spring单例下如何解决循环依赖(三级缓存)
Spring中循环依赖包括构造器依赖和setter注入依赖,Spring只能解决单例setter注入依赖(注入时会返回提前暴露的创建中的bean),构造器依赖无法解决(因为只有实例化之后才能曝光,实例化前曝光是有风险的),对于原型模式,循环依赖也是无法解决的(因为不使用缓存)
bean什么时候才会提早曝光:单例、创建中、允许循环依赖
1、尝试从singletionObjects中获取实例
2、尝试从earlySingletionObjects中获取实例
3、根据beanName尝试从singletonFactories中获取ObjectFactory,调用getObject方法创建bean(这里只是实例化了bean),放到earlySingletionObjects中,并从singletonFactories中移除ObjectFactory(互斥操作)这时已经可以通过容器的getBean方法获取到bean