Spring Bean生命周期全解析

Spring Bean生命周期详解:从创建到销毁的完整过程

Spring Bean的生命周期是Spring框架的核心概念之一,理解这一过程对于掌握Spring IoC容器的工作原理至关重要。Bean的生命周期涵盖了从实例化到销毁的完整过程,期间涉及多个关键阶段和扩展点。

一、Bean生命周期核心阶段

阶段序号 生命周期阶段 核心作用 关键接口/注解
1 实例化(Instantiation) 创建Bean实例 构造函数
2 属性赋值(Populate) 依赖注入 @Autowired, @Value
3 初始化(Initialization) 自定义初始化 @PostConstruct, InitializingBean
4 使用(Ready) Bean就绪可用 -
5 销毁(Destruction) 资源清理 @PreDestroy, DisposableBean

二、详细生命周期流程

1. 实例化阶段

Bean的实例化是生命周期的起点,Spring容器通过反射机制调用Bean的构造函数创建对象实例。

java 复制代码
public class UserService {
    public UserService() {
        System.out.println("1. Bean实例化 - 构造函数执行");
    }
}

在此阶段,Spring会根据BeanDefinition中的配置信息来决定使用哪种实例化策略。

2. 属性赋值阶段

实例化完成后,Spring容器会进行依赖注入,为Bean的属性设置值。

java 复制代码
@Component
public class UserService {
    @Autowired
    private UserRepository userRepository;
    
    @Value("${app.name}")
    private String appName;
    
    // 属性设置方法
    public void setUserRepository(UserRepository userRepository) {
        System.out.println("2. 属性赋值 - 依赖注入");
        this.userRepository = userRepository;
    }
}

这个阶段还包括处理@Autowired@Resource@Value等注解的自动装配。

3. Aware接口回调

如果Bean实现了各种Aware接口,Spring会在初始化前调用相应的方法:

java 复制代码
@Component
public class CustomBean implements BeanNameAware, BeanFactoryAware, ApplicationContextAware {
    
    @Override
    public void setBeanName(String name) {
        System.out.println("3.1 BeanNameAware - Bean名称: " + name);
    }
    
    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("3.2 BeanFactoryAware - 获取BeanFactory");
    }
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("3.3 ApplicationContextAware - 获取ApplicationContext");
    }
}

Aware接口让Bean能够感知到Spring容器的存在。

4. BeanPostProcessor前置处理

BeanPostProcessor提供了在Bean初始化前后进行自定义处理的能力:

java 复制代码
@Component
public class CustomBeanPostProcessor implements BeanPostProcessor {
    
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("4.1 BeanPostProcessor前置处理 - Bean: " + beanName);
        return bean;
    }
    
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("4.2 BeanPostProcessor后置处理 - Bean: " + beanName);
        return bean;
    }
}

5. 初始化阶段

初始化阶段包含多个执行顺序严格的方法:

java 复制代码
@Component
public class UserService implements InitializingBean {
    
    @PostConstruct
    public void initMethod() {
        System.out.println("5.1 @PostConstruct注解方法执行");
    }
    
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("5.2 InitializingBean.afterPropertiesSet()方法执行");
    }
    
    // XML配置的init-method
    public void customInit() {
        System.out.println("5.3 自定义init-method方法执行");
    }
}

执行顺序为:@PostConstructInitializingBean.afterPropertiesSet() → 自定义init-method。

6. BeanPostProcessor后置处理

在初始化完成后,BeanPostProcessor的后置处理方法会被调用,这个阶段常用于AOP代理的创建:

java 复制代码
@Component
public class AopBeanPostProcessor implements BeanPostProcessor {
    
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 创建AOP代理
        if (bean instanceof UserService) {
            System.out.println("6. 创建AOP代理");
            return createProxy(bean);
        }
        return bean;
    }
}

7. 使用阶段

Bean完全初始化后进入就绪状态,可以被应用程序使用:

java 复制代码
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    
    @GetMapping("/users")
    public List<User> getUsers() {
        // Bean处于使用阶段
        return userService.findAllUsers();
    }
}

8. 销毁阶段

当Spring容器关闭时,会触发Bean的销毁过程:

java 复制代码
@Component
public class UserService implements DisposableBean {
    
    @PreDestroy
    public void preDestroy() {
        System.out.println("8.1 @PreDestroy注解方法执行");
    }
    
    @Override
    public void destroy() throws Exception {
        System.out.println("8.2 DisposableBean.destroy()方法执行");
    }
    
    // XML配置的destroy-method
    public void customDestroy() {
        System.out.println("8.3 自定义destroy-method方法执行");
    }
}

销毁方法的执行顺序为:@PreDestroyDisposableBean.destroy() → 自定义destroy-method。

三、完整生命周期流程图

graph TD A[Bean实例化] --> B[属性赋值/依赖注入] B --> C[Aware接口回调] C --> D[BeanPostProcessor前置处理] D --> E[初始化方法] E --> F[BeanPostProcessor后置处理] F --> G[Bean就绪可用] G --> H[容器关闭] H --> I[销毁方法执行]

四、实际应用场景示例

数据库连接池管理

java 复制代码
@Component
public class DatabaseConnectionPool implements InitializingBean, DisposableBean {
    
    private DataSource dataSource;
    private ConnectionPool pool;
    
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化数据库连接池");
        this.pool = new ConnectionPool(dataSource);
        this.pool.initialize();
    }
    
    @Override
    public void destroy() throws Exception {
        System.out.println("关闭数据库连接池");
        if (pool != null) {
            pool.close();
        }
    }
    
    // 业务方法
    public Connection getConnection() throws SQLException {
        return pool.getConnection();
    }
}

缓存管理器

java 复制代码
@Component
public class CacheManager implements BeanNameAware {
    
    private String beanName;
    private Map<String, Object> cache = new ConcurrentHashMap<>();
    
    @PostConstruct
    public void initializeCache() {
        System.out.println("初始化缓存管理器: " + beanName);
        // 加载初始缓存数据
        loadInitialData();
    }
    
    @PreDestroy
    public void cleanup() {
        System.out.println("清理缓存资源");
        cache.clear();
    }
    
    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }
    
    public void put(String key, Object value) {
        cache.put(key, value);
    }
    
    public Object get(String key) {
        return cache.get(key);
    }
}

五、生命周期扩展点总结

Spring Bean生命周期提供了丰富的扩展点,让开发者能够在不同阶段介入Bean的创建和管理过程:

  1. 实例化扩展:通过自定义InstantiationAwareBeanPostProcessor控制实例化过程
  2. 属性注入扩展:使用BeanPostProcessor修改属性值
  3. 初始化扩展:多种初始化方法的组合使用
  4. 销毁扩展:确保资源正确释放

理解Spring Bean的完整生命周期有助于开发者更好地利用Spring框架的特性,编写出更加健壮和可维护的应用程序。通过合理使用各个扩展点,可以实现复杂的业务需求,如性能监控、事务管理、AOP代理等高级功能。


参考来源

相关推荐
愚公移码5 分钟前
蓝凌EKP18产品:流程引擎技术篇之流程核心概念模型
java·人工智能·流程引擎·蓝凌
Full Stack Developme12 分钟前
Apache Tika 教程
java·开发语言·python·apache
鹅城剑仙27 分钟前
Java线程池完全指南
java
李白的天不白29 分钟前
SmartAdmin(基于 Spring Boot 框架)中配置跨域请求 VUE3 设置请求头
java·前端
橙子进阶之路31 分钟前
Java线程(CompletableFuture)
java·开发语言
鹅城剑仙39 分钟前
Java CompletableFuture 异步编程完全指南
java
2601_9618752442 分钟前
法考备考计划表|学习计划|资料已整理
java·开发语言·学习·eclipse·tomcat·c#·hibernate
重生之我是Java开发战士1 小时前
【Java SE】多线程(三):单例模式,阻塞队列,线程池与定时器
java·javascript·单例模式
AI人工智能+电脑小能手1 小时前
【大白话说Java面试题 第115题】【并发篇】第15题:说一下悲观锁和乐观锁的区别?
java·开发语言·面试
心之伊始1 小时前
Spring Boot Actuator + Micrometer 实战:自定义业务指标并接入 Prometheus 观测接口耗时
java·spring boot·prometheus·actuator·micrometer