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. 初始化阶段的执行顺序:@PostConstructInitializingBean#afterPropertiesSet → 自定义 init-method;销毁阶段反之。
相关推荐
GreenTea2 小时前
深度解读 Anthropic 多智能体报告:更强的模型 ≠ 更好的协调
前端·后端·算法
风流 少年2 小时前
Spring AI 2.0:Memory
java·后端·spring
万少3 小时前
给 DeepSeek Harness 装个"应用商店":一条命令,595 个插件随你逛
前端·javascript·后端
Java成神之路-5 小时前
Spring Cloud 微服务契约先行:为什么 Controller 建议要实现 Feign 接口?
spring·spring cloud·微服务
IT_陈寒7 小时前
Python的GIL让我多写了500行代码
前端·人工智能·后端
Flittly8 小时前
【雕虫大技】Agent 动态 Skill 供应链安全加固(三):输出校验与治理闭环实战
java·spring boot·spring
IT爱学堂8 小时前
精讲软件设计师(软考中级)一站式通关课_实战课程_慕课网
后端
战天战地站房顶8 小时前
在 Windows Docker 中部署 PostgreSQL 17 + pgvector 完整指南
后端
卷无止境8 小时前
FastAPI Guard 全解析,从概念到工程落地的实战指南
后端·python
卷无止境8 小时前
FastAPI Users 全面解析:概念、原理与工程实战
后端·python