弗兰的悲惨之旅
99.73M · 2026-04-04
flowchart LR
A[实例化<br/>创建对象] --> B[属性赋值<br/>依赖注入]
B --> C[初始化<br/>执行初始化逻辑]
C --> D[使用<br/>提供服务]
D --> E[销毁<br/>释放资源]
| 阶段 | 说明 | 关键操作 |
|---|---|---|
| 实例化 | 创建 Bean 对象 | 调用构造器 |
| 属性赋值 | 注入依赖 | setter 注入、@Autowired 注入 |
| 初始化 | 执行初始化逻辑 | @PostConstruct、InitializingBean、init-method |
| 使用 | 提供服务 | 业务方法调用 |
| 销毁 | 释放资源 | @PreDestroy、DisposableBean、destroy-method |
flowchart LR
Start["Bean 生命周期开始"] --> Phase1
subgraph Phase1 ["第一阶段:基础构建"]
direction TB
A["1. 实例化 Bean"] --> B["2. 设置属性"]
end
Phase1 --> Phase2
subgraph Phase2 ["第二阶段:Aware 接口回调"]
direction TB
C["3. BeanNameAware"] --> D["4. BeanFactoryAware"]
D --> E["5. ApplicationContextAware"]
end
Phase2 --> Phase3
subgraph Phase3 ["第三阶段:初始化处理"]
direction TB
F["6. BeanPostProcessor-Before"] --> G["7. @PostConstruct"]
G --> H["8. InitializingBean.afterPropertiesSet"]
H --> I["9. init-method"]
I --> J["10. BeanPostProcessor-After"]
end
Phase3 --> K["11. Bean 就绪"]
K --> Phase4
subgraph Phase4 ["第四阶段:销毁过程"]
direction TB
L["12. 容器关闭"] --> M["13. @PreDestroy"]
M --> N["14. DisposableBean.destroy"]
N --> O["15. destroy-method"]
end
// org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) {
// 1. 实例化 Bean
Object bean = doCreateBean(beanName, mbd, args);
return bean;
}
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, Object[] args) {
// 1. 实例化 Bean(创建对象)
Object bean = instanceWrapper.getWrappedInstance();
// 2. 属性赋值(依赖注入)
populateBean(beanName, mbd, instanceWrapper);
// 3. 初始化 Bean
Object exposedObject = initializeBean(beanName, bean, mbd);
return exposedObject;
}
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
// 1.1 获取构造器
Constructor<?> ctorToUse = mbd.getResolvedConstructorFactoryMethod();
// 1.2 使用反射创建对象
return bwCreator.newInstance(ctorToUse, args);
}
关键点:
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
// 2.1 执行 InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return; // 返回 false 则跳过属性赋值
}
// 2.2 执行 InstantiationAwareBeanPostProcessor#postProcessProperties
PropertyValues pvs = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
// 2.3 应用属性值
applyPropertyValues(beanName, mbd, bw, pvs);
}
关键点:
AutowiredAnnotationBeanPostProcessor#postProcessPropertiesCommonAnnotationBeanPostProcessor#postProcessPropertiesapplyPropertyValuesprotected Object initializeBean(String beanName, Object bean, RootBeanDefinition mbd) {
// 3.1 执行 Aware 接口
invokeAwareMethods(beanName, bean);
// 3.2 执行 BeanPostProcessor#postProcessBeforeInitialization
Object wrappedBean = applyBeanPostProcessorsBeforeInitialization(bean, beanName);
// 3.3 执行初始化回调
invokeInitMethods(beanName, wrappedBean, mbd);
// 3.4 执行 BeanPostProcessor#postProcessAfterInitialization
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
return wrappedBean;
}
sequenceDiagram
participant Client
participant Container as Spring 容器
participant BPP as BeanPostProcessor
participant Bean as Bean 对象
Client->>Container: getBean("userService")
Container->>Container: 1. 实例化(new UserService)
Container->>Bean: 2. 属性赋值(setUserRepository)
Container->>Bean: 3. BeanNameAware.setBeanName
Container->>Bean: 4. BeanFactoryAware.setBeanFactory
Container->>Bean: 5. ApplicationContextAware.setApplicationContext
Container->>BPP: 6. postProcessBeforeInitialization
BPP-->>Container: 返回 Bean 或 Proxy
Container->>Bean: 7. @PostConstruct
Container->>Bean: 8. InitializingBean.afterPropertiesSet
Container->>Bean: 9. init-method
Container->>BPP: 10. postProcessAfterInitialization
BPP-->>Container: 返回 Bean 或 Proxy(AOP)
Container-->>Client: 返回 Bean
public interface BeanPostProcessor {
/**
* 初始化前回调
* 在 @PostConstruct、InitializingBean、init-method 之前执行
*/
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean; // 返回原 Bean 或代理对象
}
/**
* 初始化后回调
* 在 @PostConstruct、InitializingBean、init-method 之后执行
* AOP 代理在此创建
*/
@Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean; // 返回原 Bean 或代理对象(AOP)
}
}
flowchart TD
A[属性赋值完成] --> B[Aware 接口回调]
B --> C["BeanPostProcessor<br/>postProcessBeforeInitialization"]
C --> D["@PostConstruct"]
D --> E["InitializingBean<br/>afterPropertiesSet"]
E --> F["init-method"]
F --> G["BeanPostProcessor<br/>postProcessAfterInitialization"]
G --> H[AOP 代理创建]
| BeanPostProcessor | 应用场景 | 执行时机 |
|---|---|---|
AutowiredAnnotationBeanPostProcessor | @Autowired 注入 | postProcessProperties |
CommonAnnotationBeanPostProcessor | @Resource、@PostConstruct、@PreDestroy | postProcessProperties、postProcessBeforeInitialization |
ApplicationContextAwareProcessor | Aware 接口回调 | postProcessBeforeInitialization |
AbstractAutoProxyCreator | AOP 代理创建 | postProcessAfterInitialization |
@Component
public class CustomBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) {
if ("userService".equals(beanName)) {
System.out.println("初始化前回调:" + beanName);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if ("userService".equals(beanName)) {
System.out.println("初始化后回调:" + beanName);
}
return bean;
}
}
执行顺序:
BeanPostProcessorBeanPostProcessorOrdered 接口 → @Order 注解 → 注册顺序public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
/**
* 实例化前回调
* 可以返回代理对象,跳过默认实例化逻辑
*/
@Nullable
default Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
return null; // 返回 null 则继续默认实例化
}
/**
* 实例化后回调
* 可以在属性赋值前修改 Bean 状态
*/
default boolean postProcessAfterInstantiation(Object bean, String beanName) {
return true; // 返回 false 则跳过属性赋值
}
/**
* 属性赋值回调
* 可以修改属性值
*/
@Nullable
default PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
return pvs; // 返回修改后的属性值
}
}
flowchart TD
A[1. postProcessBeforeInstantiation] --> B{返回代理?}
B -->|是| C[跳过实例化]
B -->|否| D[2. 实例化 Bean]
D --> E[3. postProcessAfterInstantiation]
E --> F{返回 true?}
F -->|否| G[跳过属性赋值]
F -->|是| H[4. postProcessProperties]
H --> I[5. 应用属性值]
I --> J[6. Aware 回调]
| InstantiationAwareBeanPostProcessor | 应用场景 |
|---|---|
AutowiredAnnotationBeanPostProcessor | @Autowired 注入 |
CommonAnnotationBeanPostProcessor | @Resource 注入 |
RequiredAnnotationBeanPostProcessor | @Required 检查 |
@Component
public class UserService {
// 方式1:@PostConstruct 注解
@PostConstruct
public void init1() {
System.out.println("方式1:@PostConstruct");
}
}
// 方式2:InitializingBean 接口
@Component
public class UserService implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("方式2:InitializingBean");
}
}
// 方式3:init-method
@Configuration
public class AppConfig {
@Bean(initMethod = "init3")
public UserService userService() {
return new UserService();
}
}
public class UserService {
public void init3() {
System.out.println("方式3:init-method");
}
}
flowchart LR
A["@PostConstruct"] --> B["InitializingBean<br/>afterPropertiesSet"]
B --> C["init-method"]
执行顺序:
推荐使用:@PostConstruct(标准化、不耦合 Spring)
// 方式1:@PreDestroy 注解
@Component
public class UserService {
@PreDestroy
public void destroy1() {
System.out.println("方式1:@PreDestroy");
}
}
// 方式2:DisposableBean 接口
@Component
public class UserService implements DisposableBean {
@Override
public void destroy() throws Exception {
System.out.println("方式2:DisposableBean");
}
}
// 方式3:destroy-method
@Configuration
public class AppConfig {
@Bean(destroyMethod = "destroy3")
public UserService userService() {
return new UserService();
}
}
public class UserService {
public void destroy3() {
System.out.println("方式3:destroy-method");
}
}
flowchart LR
A["@PreDestroy"] --> B["DisposableBean<br/>destroy"]
B --> C["destroy-method"]
执行顺序:
// 方式1:关闭容器
ConfigurableApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
context.close(); // 触发销毁
// 方式2:注册关闭钩子
ConfigurableApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
context.registerShutdownHook(); // JVM 关闭时触发销毁
// 方式3:使用 try-with-resources(Spring 5+)
try (ConfigurableApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class)) {
// 使用容器
} // 自动关闭,触发销毁
// Bean 创建核心类
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory
- #createBean() // 创建 Bean
- #doCreateBean() // 执行创建
- #createBeanInstance() // 实例化
- #populateBean() // 属性赋值
- #initializeBean() // 初始化
// BeanPostProcessor 接口
org.springframework.beans.factory.config.BeanPostProcessor
org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor
// 典型实现
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor
org.springframework.context.annotation.CommonAnnotationBeanPostProcessor
org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator
// Aware 回调接口
org.springframework.beans.factory.BeanNameAware
org.springframework.beans.factory.BeanFactoryAware
org.springframework.context.ApplicationContextAware
// 初始化回调接口
javax.annotation.PostConstruct // @PostConstruct
org.springframework.beans.factory.InitializingBean // InitializingBean
org.springframework.beans.factory.DisposableBean // DisposableBean
javax.annotation.PreDestroy // @PreDestroy