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;销毁阶段反之。
相关推荐
PPPPickup2 小时前
深信服公司---java实习生后端一二面询问
java·后端·ai
架构师沉默2 小时前
为什么很多大厂 API 不再使用 PUT 和 DELETE?
java·后端·架构
回家路上绕了弯2 小时前
Claude Code Agent Team 全解析:AI 集群协作,重构代码开发新范式
人工智能·分布式·后端
树獭叔叔3 小时前
扩散模型完全指南:从直觉到数学的深度解析
后端·aigc·openai
毕设源码_严学姐3 小时前
计算机毕业设计springboot心理健康辅导系统 高校学生心灵关怀服务平台的设计与实现 校园智慧心理服务系统的设计与实现
spring boot·后端·课程设计
程序员牛奶3 小时前
如何使用Redis Set实现简单的抽奖系统?
后端
程序员海军3 小时前
深度测评:在微信里直接操控 OpenClaw
人工智能·后端
野犬寒鸦3 小时前
面试常问:HTTP 1.0 VS HTTP 2.0 VS HTTP 3.0 的核心区别及底层实现逻辑
服务器·开发语言·网络·后端·面试
砍材农夫3 小时前
多层缓存设计
后端