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代理等高级功能。


参考来源

相关推荐
ok_hahaha2 小时前
java从头开始-苍穹外卖-day06-微信小程序开发-微信登录和商品浏览
java·微信·微信小程序·小程序
Java面试题总结2 小时前
Spring @Validated失效?原因、排查与高效解决方案全解析
java·spring boot·spring
剑锋所指,所向披靡!2 小时前
MySQL数据的增删改查
java·数据库·mysql
Villiam_AY2 小时前
一次 DNS 端口引发的代理网络和公司内网冲突问题
java·服务器·数据库
dgvri2 小时前
比较Spring AOP和AspectJ
java
eggwyw2 小时前
springboot和springframework版本依赖关系
java·spring boot·后端
于先生吖4 小时前
国际版JAVA婚恋交友系统源码:多语言适配,可商用的跨境婚恋解决方案
java·大数据·交友
fengci.4 小时前
ctfshow(web入门)279-286
java·开发语言·学习