- bean工厂组织结构调用
- 主要涉及 类接口
BeanFactory
AbstractBeanFactory
AbstractAutowireCapableBeanFactory
DefaultListableBeanFactory
- 调用入口
- 调用类 DefaultListableBeanFactory
// 实例化不是懒加载的的实例bean
finishBeanFactoryInitialization(beanFactory);
// 实例化不是懒加载的的实例bean
beanFactory.preInstantiateSingletons(); //beanFactory: DefaultListableBeanFactory
preInstantiateSingletons 方法
- 筛选非懒加载所有bean
- 判断是否是工厂bean ,拼接 工厂bean FACTORY_BEAN_PREFIX前缀的名称
- 调用getBean方法实例化bean
- 触发所有适用bean的初始化后回调
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
}
// Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// 触发所有非懒加载的bean执行实例化
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
final FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
}
else {
getBean(beanName);
}
}
}
// 触发所有适用bean的初始化后回调
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
- 调用类 AbstractBeanFactory
getBean(String name) throws BeansException
1.判断 是否是手动创建的bean 实例, 调用getObjectForBeanInstance获取bean对象实例
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
2. 该工厂中不存在bean定义,调用上下文父类 工厂 实例化bean 对象
- bean实例,则失败:大概在循环引用中;
- bean定义。
- bean 名字、参数创建
- 通过bean 名字、类型创建
- bean 名字创建
- 则标记为已创建
// 如果我们已经在创建此bean实例,则失败:大概在循环引用中。
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
//检查该工厂中是否存在bean定义
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
3.根据传入的参数获取合并BeanDefinition对象并检查对象,确保当前bean依赖的bean的初始化。
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// 确保当前bean依赖的bean的初始化
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
4.根据BeanDefinition 实例化不同类型的bean 实例
- mbd.isSingleton():单例实例创建 调用 getSingleton(beanName, () -> {}) 执行 AbstractAutowireCapableBeanFactory类方法 createBean(beanName, mbd, args) 创建实例
- mbd.isPrototype() : 原型实例创建 调用 beforePrototypeCreation(beanName) -》 createBean(beanName, mbd, args) -》 afterPrototypeCreation(beanName)
- mbd.getScope() : 范围实例 创建 调用 scope.get(beanName, () -> {}}) 执行 beforePrototypeCreation(beanName) -》 createBean(beanName, mbd, args) -》 afterPrototypeCreation(beanName)
beforePrototypeCreation afterPrototypeCreation方法 操作prototypesCurrentlyInCreation 字段 ,利用线程副本 ,保证每个线程中只有一个唯一bean对象在创建。
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final 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, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
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",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
5.检查所需的类型是否与实际bean实例的类型匹配
- 获取类型转换器进行必要时的类型装换
// 检查所需的类型是否与实际bean实例的类型匹配
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
- 调用类 AbstractAutowireCapableBeanFactory
调用方法:createBean
Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException
- bean类,并在无法动态存储的Class不能存储在共享合并bean定义中的情况下克隆bean定义
- resolveBeforeInstantiation() 给BeanPostProcessors一个返回代理而不是目标bean实例的机会 ,针对InstantiationAwareBeanPostProcessor 实现类调用实例化之前的后期处理方法
- doCreateBean方法实例化对象
resolveBeforeInstantiation() 调用需要代理的类中,用于aop中 AbstractAutoProxyCreator类 创建bean实例的代理类
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// 确保此时确实解析了bean类,并在无法动态存储的Class不能存储在共享合并bean定义中的情况下克隆bean定义
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一个返回代理而不是目标bean实例的机会
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);
}
try {
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
调用方法:doCreateBean
Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) throws BeanCreationException
1.创建bean实例并实例化为bean包装BeanWrapper类
- 获取实例并清除工厂实例缓存
- createBeanInstance(beanName, mbd, args)方法实例化bean 以及包装类
- bean实例 以及 bean 类型
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
2. 允许后处理器修改合并的bean定义
调用applyMergedBeanDefinitionPostProcessors( )方法合并的bean定义
标记bean 已定义后处理器
//允许后处理器修改合并的bean定义
if (!mbd.postProcessed) {
try {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
createBeanInstance() 使用适当的实例化策略为指定的Bean创建一个新实例:工厂方法,构造函数自动装配或简单实例化
3. 急于缓存单例,以便即使在诸如BeanFactoryAware之类的生命周期接口触发时也能够解析循环引用。
//急于缓存单例,以便即使在诸如BeanFactoryAware之类的生命周期接口触发时也能够解析循环引用。
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
4.初始化bean 实例
调用populateBean(beanName, mbd, instanceWrapper) 填充bean实例 ,使用Bean定义中的属性值填充给定BeanWrapper中的Bean实例。
调用initializeBean(beanName, exposedObject, mbd) 初始化bean实例 ,执行 Aware方法填充参数-》调用 后置处理器applyBeanPostProcessorsBeforeInitialization方法-》执行Init方法:afterPropertiesSet() -》调用 后置处理器applyBeanPostProcessorsAfterInitialization方法
populateBean(beanName, mbd, instanceWrapper) 使用Bean定义中的属性值填充给定BeanWrapper中的Bean实例
执行InstantiationAwareBeanPostProcessor 后置处理器实现类 的postProcessAfterInstantiation() 方法
判断自动注解模式 byName 执行autowireByType()方法,还是byType 执行 autowireByType()方法
执行InstantiationAwareBeanPostProcessor 后置处理器实现类 的postProcessProperties() 方法
判断是否需要进行依赖检查,调用applyPropertyValues()方法 应用bean 实例参数 ,执行setPropertyValues() 进行深度复制
initializeBean()方法 执行bean后处理器初始化
使用工厂回调以及初始化方法和bean后处理器初始化给定的bean实例。 对于传统定义的bean,从createBean调用,对于现有的bean实例,从initializeBean调用。
Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
invokeAwareMethods(beanName, bean); // 设置 BeanNameAware 、 BeanClassLoaderAware、 BeanFactoryAware 方法参数注入
applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); //执行BeanPostProcessors后置处理器 postProcessBeforeInitialization()
invokeInitMethods(beanName, wrappedBean, mbd); //执行 InitializingBean 实现并且不是外部管理的初始化方法的bean afterPropertiesSet()
applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); //执行BeanPostProcessors后置处理器 postProcessAfterInitialization()
// 初始化bean 实例
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
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);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
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.");
}
}
}
}