Spring Bean生命周期与循环依赖深度解析
·
Spring Bean生命周期与循环依赖深度解析
目录
引言
Spring框架作为Java企业级开发的事实标准,其核心思想之一就是控制反转(IoC)和依赖注入(DI)。理解Spring Bean的生命周期,特别是Bean的创建、初始化、销毁全过程,是深入掌握Spring框架的必经之路。
同时,循环依赖问题是Spring开发中常见的技术难点,理解其原理对于解决实际项目问题具有重要意义。
本文将从源码级别深入剖析:
- Spring Bean的完整生命周期
- 三级缓存机制的工作原理
- 循环依赖的检测与解决策略
- 无法解决的循环依赖场景
1. Bean生命周期完整流程
1.1 整体流程图
1.2 源码入口
// AbstractBeanFactory.doGetBean() - Bean创建入口
protected <T> T doGetBean(
String name,
Class<T> requiredType,
Object[] args,
boolean typeCheckOnly) throws BeansException {
// 1. 获取合并后的BeanDefinition
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// 2. 标记为正在创建
beforeSingletonCreation(beanName);
// 3. 创建Bean
try {
return createBean(beanName, mbd, args);
} finally {
afterSingletonCreation(beanName);
}
}
2. 实例化阶段
2.1 createBean核心流程
// AbstractAutowireCapableBeanFactory.createBean()
@Override
protected Object createBean(
String beanName,
RootBeanDefinition mbd,
Object[] args) {
// 1. 检查InstantiationAwareBeanPostProcessor
// 处理Bean实例化前的回调
Object bean = resolveBeforeInstantiation(beanName, mbd);
if (bean != null) {
return bean; // 如果返回了bean,跳过常规创建流程
}
// 2. 执行常规创建流程
Object beanInstance = doCreateBean(beanName, mbd, args);
return beanInstance;
}
2.2 InstantiationAwareBeanPostProcessor
/**
* 实例化前置处理器
* 可以决定是否跳过默认的构造函数创建逻辑
*/
public interface InstantiationAwareBeanPostProcessor
extends BeanPostProcessor {
/**
* 在构造函数执行前返回自定义Bean实例
*/
@Nullable
default Object postProcessBeforeInstantiation(
Class<?> beanClass, String beanName) throws BeansException {
return null;
}
/**
* 在构造函数执行后返回自定义Bean实例
*/
default boolean postProcessAfterInstantiation(
Object bean, String beanName) throws BeansException {
return true;
}
/**
* 处理属性值(如@Value注解)
*/
@Nullable
default PropertyValues postProcessPropertyValues(
PropertyValues pvs,
PropertyDescriptor[] pds,
Object bean, String beanName) throws BeansException {
return pvs;
}
}
2.3 构造函数选择策略
// ConstructorResolver.autowireConstructor()
private BeanWrapper autowireConstructor(
String beanName,
RootBeanDefinition mbd,
Constructor<?>[] chosenCtors,
Object[] explicitArgs) {
// 1. 如果显式指定了参数,直接使用
if (explicitArgs != null) {
return new ConstructorResolver(this).instantiateUsingFactoryMethod(
beanName, mbd, chosenCtors, explicitArgs);
}
// 2. 否则,自动推断构造函数
Constructor<?>[] constructors = chosenCtors != null ?
chosenCtors : mbd.getConstructors();
// 3. 使用ConstructorResolver推断最优构造函数
return new ConstructorResolver(this).autowireConstructor(
beanName, mbd, constructors, null);
}
2.4 实例化后处理
// AbstractAutowireCapableBeanFactory.doCreateBean()
protected Object doCreateBean(
String beanName,
RootBeanDefinition mbd,
Object[] args) {
// 1. 创建BeanWrapper
BeanWrapper instanceWrapper = createBeanInstance(beanName, mbd, args);
// 2. 获取原始Bean
final Object bean = instanceWrapper.getWrappedInstance();
// 3. 【关键】将正在创建的Bean放入三级缓存
// 用于解决循环依赖
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
// 4. 处理属性填充
populateBean(beanName, mbd, instanceWrapper);
// 5. 初始化Bean
Object exposedObject = initializeBean(beanName, exposedObject, mbd);
return exposedObject;
}
3. 属性填充阶段
3.1 populateBean核心流程
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
// 1. 执行InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation
// 可以在这里终止属性填充
if (!mbd.getPropertyValues().isEmpty() || mbd.getPropertyValues() != null) {
giveBeanInstance = applyInstantiationAwareBeanPostProcessorAfterInstantiation(
beanName, bean, mbd, pv);
}
// 2. 处理自动装配模式
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
MutablePropertyValues mpv = new MutablePropertyValues(pvs);
// 按名称自动装配
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, mpv);
}
// 按类型自动装配
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, mpv);
}
pvs = mpv;
}
// 3. 处理@Value和@Autowired注解
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 【关键】AutowiredAnnotationBeanPostProcessor在这里处理@Autowired
PropertyValues pvsToUse = ibp.postProcessPropertyValues(
pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return; // 返回null表示跳过属性填充
}
pvs = pvsToUse;
}
}
// 4. 应用属性值
applyPropertyValues(beanName, mbd, bw, pvs);
}
3.2 AutowiredAnnotationBeanPostProcessor
// AutowiredAnnotationBeanPostProcessor处理@Autowired
@Override
public PropertyValues postProcessPropertyValues(
PropertyValues pvs,
PropertyDescriptor[] pds,
Object bean, String beanName) throws BeansException {
// 1. 查找所有需要自动装配的属性和方法
InjectionMetadata metadata = findAutowiringMetadata(
bean.getClass(), beanName, pvs);
try {
// 2. 执行依赖注入
metadata.inject(bean, beanName, pvs);
} catch (BeanCreationException ex) {
throw ex;
}
return pvs;
}
3.3 依赖注入详解
// AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement
private class AutowiredFieldElement extends InjectionElement {
@Override
protected void inject(Object bean, String beanName, PropertyValues pvs)
throws Throwable {
Field field = (Field) this.member;
try {
// 1. 查找要注入的Bean
Object value = resolveFieldValue(field, bean, beanName);
// 2. 反射设置字段值
ReflectionUtils.makeAccessible(field);
field.set(bean, value);
} catch (Throwable ex) {
throw new BeanCreationException(
"Could not autowire field: " + field, ex);
}
}
}
@Override
protected Object resolveFieldValue(Field field, Object bean, String beanName) {
// 1. 创建依赖描述符
DependencyDescriptor descriptor = new DependencyDescriptor(field, this.required);
// 2. 解析依赖
Object result = beanFactory.resolveDependency(
descriptor, beanName, autowiredBeanNames, typeConverter);
return result;
}
4. 初始化阶段
4.1 initializeBean核心流程
protected Object initializeBean(
String beanName,
Object bean,
RootBeanDefinition mbd) {
// 1. 安全处理
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(() -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
} else {
// 2. 【关键】处理Aware接口回调
invokeAwareMethods(beanName, bean);
}
// 3. 【关键】执行BeanPostProcessor前置处理
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(
wrappedBean, beanName);
}
// 4. 【关键】执行初始化方法
try {
invokeInitMethods(beanName, wrappedBean, mbd);
} catch (Throwable ex) {
throw new BeanCreationException(
beanName, mbd.getResourceDescription(), "Invocation of init method failed", ex);
}
// 5. 【关键】执行BeanPostProcessor后置处理
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(
wrappedBean, beanName);
}
return wrappedBean;
}
4.2 Aware接口回调
private void invokeAwareMethods(String beanName, 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(this);
}
}
}
4.3 初始化方法执行
protected void invokeInitMethods(
String beanName,
Object bean,
RootBeanDefinition mbd) throws Throwable {
// 1. 执行InitializingBean接口
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean) {
((InitializingBean) bean).afterPropertiesSet();
}
// 2. 执行自定义init-method
if (mbd.hasInitMethodName()) {
String initMethodName = mbd.getInitMethodName();
Method initMethod = determineCommonMethod(initMethodName);
if (initMethod != null) {
invokeCustomInitMethod(beanName, bean, initMethod);
}
}
}
// InitializingBean接口定义
public interface InitializingBean {
/**
* Bean属性填充完成后调用
* @throws Exception 如果初始化失败
*/
void afterPropertiesSet() throws Exception;
}
4.4 BeanPostProcessor前置处理
@Override
public Object applyBeanPostProcessorsBeforeInitialization(
Object existingBean, String beanName) throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(
result, beanName);
if (current == null) {
return result; // 返回null表示短路,后续处理器不会执行
}
result = current;
}
return result;
}
常用BeanPostProcessor前置处理:
// 1. ApplicationContextAwareProcessor
// 设置ApplicationContext等感知接口
class ApplicationContextAwareProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(
Object bean, String beanName) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(
getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
// ...
}
// ... 其他Aware接口
return bean;
}
}
// 2. InitDestroyAnnotationBeanPostProcessor
// 处理@PostConstruct和@PreDestroy
class InitDestroyAnnotationBeanPostProcessor
implements DestructionAwareBeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(
Object bean, String beanName) throws BeansException {
LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
// 执行@PostConstruct方法
metadata.invokeInitMethods(bean, beanName);
return bean;
}
}
5. 销毁阶段
5.1 销毁流程图
5.2 销毁接口定义
public interface DisposableBean {
/**
* Bean销毁时调用
* @throws Exception 如果销毁失败
*/
void destroy() throws Exception;
}
5.3 销毁注册
// AbstractBeanFactory.registerDisposableBean()
public void registerDisposableBean(String beanName, DisposableBean bean) {
synchronized (this.disposableBeans) {
this.disposableBeans.put(beanName, bean);
}
}
// DestrupctionAwareBeanPostProcessor
public interface DestructionAwareBeanPostProcessor extends BeanPostProcessor {
/**
* 销毁前回调
*/
void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException;
}
5.4 destroy-method处理
// DisposableBeanAdapter
public class DisposableBeanAdapter implements DisposableBean, Runnable {
private final Object bean;
private final String beanName;
private final String destroyMethodName;
private final RootBeanDefinition beanDefinition;
@Override
public void destroy() throws Exception {
// 1. 如果实现了DisposableBean,调用destroy()
if (this.bean instanceof DisposableBean) {
((DisposableBean) this.bean).destroy();
return;
}
// 2. 否则,调用自定义destroy-method
if (this.destroyMethodName != null) {
invokeCustomDestroyMethod(this.destroyMethodName);
}
}
}
6. 三级缓存机制
6.1 缓存结构
public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry {
// ========== 一级缓存:完全初始化的单例Bean ==========
// key: beanName, value: 完全初始化好的Bean
private final Map<String, Object> singletonObjects =
new ConcurrentHashMap<>(256);
// ========== 二级缓存:提前暴露的Bean(尚未完全初始化)==========
// key: beanName, value: 提前暴露的Bean引用
// 用于解决循环依赖
private final Map<String, Object> earlySingletonObjects =
new HashMap<>(16);
// ========== 三级缓存:Bean工厂 ==========
// key: beanName, value: ObjectFactory(用于创建提前暴露的Bean)
// 为什么要用ObjectFactory?因为Bean可能需要被代理
private final Map<String, ObjectFactory<?>> singletonFactories =
new HashMap<>(16);
// ========== 注册的单例集合 ==========
private final Set<String> registeredSingletons =
new LinkedHashSet<>(256);
// ========== 正在创建的单例 ==========
private final Set<String> singletonsCurrentlyInCreation =
Collections.newSetFromMap(new ConcurrentHashMap<>(16));
}
6.2 缓存交互流程
6.3 注册单例流程
// DefaultSingletonBeanRegistry.addSingleton()
protected void addSingleton(String beanName, Object singletonObject) {
synchronized (this.singletonObjects) {
// 1. 加入一级缓存
this.singletonObjects.put(beanName, singletonObject);
// 2. 从二级缓存移除(如果有)
this.earlySingletonObjects.remove(beanName);
// 3. 从三级缓存移除
this.singletonFactories.remove(beanName);
// 4. 注册单例
this.registeredSingletons.add(beanName);
}
}
6.4 提前暴露Bean
// AbstractAutowireCapableBeanFactory.doCreateBean()
protected Object doCreateBean(
String beanName,
RootBeanDefinition mbd,
Object[] args) {
// 1. 创建BeanWrapper
BeanWrapper instanceWrapper = createBeanInstance(beanName, mbd, args);
final Object bean = instanceWrapper.getWrappedInstance();
// 2. 【关键】提前暴露Bean到三级缓存
// 用于解决循环依赖
boolean earlySingletonExposure =
(mbd.isSingleton() && allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
// 将ObjectFactory放入三级缓存
addSingletonFactory(beanName,
() -> getEarlyBeanReference(beanName, mbd, bean));
}
// 3. 填充属性(可能触发循环依赖获取)
populateBean(beanName, mbd, instanceWrapper);
// 4. 初始化
Object exposedObject = initializeBean(beanName, exposedObject, mbd);
return exposedObject;
}
7. 循环依赖解决流程
7.1 循环依赖场景
说明:Setter注入/属性注入的循环依赖可通过三级缓存解决,但构造器注入的循环依赖无法解决,会抛出
BeanCurrentlyInCreationException。
7.2 循环依赖解决流程详解
以 A → B → A 为例:
7.3 源码实现
// DefaultSingletonBeanRegistry.getSingleton()
@Override
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// 1. 检查一级缓存
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
// 2. 检查一级缓存,同时Bean正在创建中
synchronized (this.singletonObjects) {
// 检查二级缓存
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
// 3. 【关键】检查三级缓存
ObjectFactory<?> singletonFactory =
this.singletonFactories.get(beanName);
if (singletonFactory != null) {
// 4. 从ObjectFactory获取Bean
singletonObject = singletonFactory.getObject();
// 5. 放入二级缓存
this.earlySingletonObjects.put(beanName, singletonObject);
// 6. 从三级缓存移除
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
8. 无法解决的循环依赖
8.1 构造器循环依赖
// 构造器注入的循环依赖无法解决
@Service
public class ServiceA {
public ServiceA(ServiceB serviceB) { // 构造器注入
this.serviceB = serviceB;
}
}
@Service
public class ServiceB {
public ServiceB(ServiceA serviceA) { // 构造器注入
this.serviceA = serviceA;
}
}
// 错误:BeanCurrentlyInCreationException
// 原因:构造器执行时就需要完整的依赖对象
8.2 prototype作用域循环依赖
// prototype作用域的循环依赖无法解决
@Scope("prototype")
@Service
public class PrototypeA {
@Autowired
public PrototypeA(PrototypeB prototypeB) {
this.prototypeB = prototypeB;
}
}
@Scope("prototype")
@Service
public class PrototypeB {
@Autowired
public PrototypeB(PrototypeA prototypeA) {
this.prototypeA = prototypeA;
}
}
// 错误:BeanCurrentlyInCreationException
// 原因:prototype作用域不会提前暴露到缓存
8.3 @Async异步方法的循环依赖
// @Async方法的循环依赖无法解决
@Service
public class AsyncServiceA {
@Autowired
private AsyncServiceB serviceB;
@Async
public void asyncMethod() {
// ...
}
}
@Service
public class AsyncServiceB {
@Autowired
private AsyncServiceA serviceA;
}
// 错误:BeanCurrentlyInCreationException
// 原因:@Async会产生代理,提前暴露的Bean可能不是代理对象
9. 实战:解决循环依赖
9.1 使用@Lazy延迟注入
@Service
public class ServiceA {
private final ServiceB serviceB;
// 使用@Lazy延迟注入
public ServiceA(@Lazy ServiceB serviceB) {
this.serviceB = serviceB;
}
}
@Service
public class ServiceB {
private final ServiceA serviceA;
public ServiceB(@Lazy ServiceA serviceA) {
this.serviceA = serviceA;
}
}
9.2 使用Setter注入替代构造器注入
@Service
public class ServiceA {
private ServiceB serviceB;
// Setter注入替代构造器注入
@Autowired
public void setServiceB(ServiceB serviceB) {
this.serviceB = serviceB;
}
}
@Service
public class ServiceB {
private ServiceA serviceA;
@Autowired
public void setServiceA(ServiceA serviceA) {
this.serviceA = serviceA;
}
}
9.3 使用ObjectFactory延迟获取
@Service
public class ServiceA {
private final ObjectFactory<ServiceB> serviceBFactory;
public ServiceA(ObjectFactory<ServiceB> serviceBFactory) {
this.serviceBFactory = serviceBFactory;
}
public void doSomething() {
// 真正需要时才获取
ServiceB serviceB = serviceBFactory.getObject();
serviceB.process();
}
}
9.4 使用ApplicationContextAware
@Service
public class ServiceA implements ApplicationContextAware {
private ApplicationContext context;
private ServiceB serviceB;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.context = applicationContext;
}
@Autowired
public void setServiceB(ServiceB serviceB) {
this.serviceB = serviceB;
}
}
总结
本文深入剖析了Spring Bean生命周期的完整流程和循环依赖的解决机制:
Bean生命周期:
- 实例化:通过构造器或FactoryMethod创建Bean实例
- 属性填充:处理@Autowired、@Value等注解
- 初始化:执行Aware回调、BeanPostProcessor、InitializingBean
- 销毁:执行@PreDestroy、DisposableBean.destroy()
三级缓存机制:
- 一级缓存:完全初始化的单例Bean
- 二级缓存:提前暴露的Bean(用于循环依赖)
- 三级缓存:ObjectFactory(用于创建代理)
循环依赖解决:
- Spring只能解决setter注入的循环依赖
- 构造器注入和prototype作用域的循环依赖无法解决
- 通过三级缓存和提前暴露Bean来解决
解决循环依赖的实战技巧:
- 使用@Lazy延迟注入
- 使用Setter注入替代构造器注入
- 使用ObjectFactory延迟获取
- 重构代码消除循环依赖
理解这些核心机制,对于解决实际项目中的Spring问题至关重要。
更多推荐




所有评论(0)