Spring中Bean的生命周期

Spring中Bean的生命周期

Spring 中 Bean 的生成过程是 Spring 容器核心的生命周期管理逻辑,简单来说就是 Spring 容器从配置(XML/注解/JavaConfig)中读取 Bean 定义,最终创建出可使用的 Bean 实例的全过程。

Bean 生成的核心流程

复制代码
Bean 定义加载 → 实例化(创建对象) → 属性填充(依赖注入) → 初始化(执行自定义逻辑) → 就绪(可使用) → 销毁(容器关闭)

Bean 生成的详细流程

代码示例:直观感受 Bean 生命周期

java 复制代码
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

// 标注为组件,让Spring扫描并创建Bean
@Component
public class UserBean implements BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean {

    private String name;

    // 无参构造器(实例化时调用)
    public UserBean() {
        System.out.println("1. Bean 实例化:执行构造器");
    }

    // 属性填充(依赖注入)
    public void setName(String name) {
        this.name = name;
        System.out.println("2. Bean 属性填充:设置name属性");
    }

    // ========== Aware 接口 ==========
    @Override
    public void setBeanName(String name) {
        System.out.println("3. 执行BeanNameAware:获取Bean名称=" + name);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("4. 执行BeanFactoryAware:获取BeanFactory");
    }

    // ========== 初始化相关 ==========
    @PostConstruct
    public void postConstruct() {
        System.out.println("5. 执行@PostConstruct注解方法");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("6. 执行InitializingBean#afterPropertiesSet");
    }

    // 自定义初始化方法(需要在@Bean中指定initMethod,或XML配置init-method)
    public void init() {
        System.out.println("7. 执行自定义init-method");
    }

    // ========== 销毁相关 ==========
    @PreDestroy
    public void preDestroy() {
        System.out.println("8. 执行@PreDestroy注解方法");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("9. 执行DisposableBean#destroy");
    }

    // 自定义销毁方法(需要指定destroy-method)
    public void destroyMethod() {
        System.out.println("10. 执行自定义destroy-method");
    }
}

配置类(启动容器):

java 复制代码
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan("com.example") // 扫描包下的组件
public class SpringConfig {
    public static void main(String[] args) {
        // 启动Spring容器,触发Bean创建
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        // 获取Bean(验证是否就绪)
        UserBean userBean = context.getBean(UserBean.class);
        System.out.println("Bean 就绪:" + userBean);
        // 关闭容器,触发Bean销毁
        context.close();
    }
}

输出结果(关键顺序):

markdown 复制代码
1. Bean 实例化:执行构造器
2. Bean 属性填充:设置name属性
3. 执行BeanNameAware:获取Bean名称=userBean
4. 执行BeanFactoryAware:获取BeanFactory
5. 执行@PostConstruct注解方法
6. 执行InitializingBean#afterPropertiesSet
7. 执行自定义init-method
Bean 就绪:com.example.UserBean@xxxx
8. 执行@PreDestroy注解方法
9. 执行DisposableBean#destroy
10. 执行自定义destroy-method

总结

  1. Spring Bean 生成的核心是:定义加载 → 实例化 → 属性填充 → 初始化 → 就绪 → 销毁,每个阶段都有明确的扩展点。
  2. BeanPostProcessor 是 Spring 最核心的扩展点,AOP、注解解析(如 @PostConstruct)都依赖它实现。
  3. 初始化阶段的执行顺序:@PostConstruct → InitializingBean#afterPropertiesSet → 自定义 init-method;销毁阶段反之。
相关推荐
IT_陈寒35 分钟前
Redis内存暴涨,没想到是AOF重写捣的鬼
前端·人工智能·后端
ikoala35 分钟前
让 Codex 自己查账:一个省 token 的小技巧
前端·后端·ai编程
wo_jack4 小时前
C++ 入门笔记(十六):第16课 vector 模拟实现十问十答 —— 从三指针到迭代器失效
c++·后端·面试·stl·vector
量化分析码农5 小时前
【Python量化波动率实战 02】波动率会传染:EWMA 指数加权给近期行情更大话语权
后端
GISer_Jing6 小时前
如何学习Agent
后端·langchain
JWASX7 小时前
【Go】map 源码解析 - group
后端·golang·map·源码分析
量化分析码农8 小时前
【Python量化波动率实战 01】波动率是怎么算的:年化、滚动与区间估计一次讲清
后端
特立独行的猫A8 小时前
AI 时代,我为什么推荐用 cj-tauri 开发桌面应用
java·后端·python
金銀銅鐵8 小时前
从一个类名到一张类图:用反射自动生成 PlantUML
java·后端·uml
追逐时光者9 小时前
一款基于 .NET 开源、免费的数据库自治诊断平台
后端·.net