Spring Bean生命周期中各方法的执行顺序及代码

本文详细介绍了Spring Bean的生命周期,包括从构造器实例化到对象销毁的各个阶段,如设置属性、调用Aware接口、@PostConstruct、InitializingBean、自定义初始化方法、@PreDestroy和DisposableBean等。同时,提供了实验代码来验证执行顺序。
摘要由CSDN通过智能技术生成

方法的执行顺序

  1. Bean 容器 / BeanFactory 通过对象的构造器或工厂方法先实例化 Bean;
  2. 设置对象属性
  3. 检查 xxxAware 相关接口,如果有就调用相应的 setxxx 方法把所需要的 xxx 传入到 Bean 中。
  4. 检查是否存在有关联的 BeanPostProcessors执行执行 postProcessBeforeInitialization() 方法进行前置处理
  5. 调用 @PostConstruct注解的方法
  6. 如果 Bean 实现了 InitializingBean 接口,执行 afterPropertiesSet() 方法。
  7. 检查是否配置了自定义的 init-method 属性,如果有就调用指定方法。
  8. 检查是否存在有关联的 BeanPostProcessors 执行 postProcessAfterInitialization() 方法进行后置处理
  9. 使用bean
  10. 当容器关闭时,调用@PreDestroy注解的方法
  11. 如果实现了 DisposableBean 接口,如果有就调用 destory() 方法。
  12. 如果 Bean 配置文件中的定义包含 destroy-method 属性,执行指定的方法。

实验代码

bean.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       "
       default-init-method="init_method" default-destroy-method="destroy_method">
  <context:component-scan   base-package="spring" />
  <bean class="spring.InitHelloWorld"/>
  <bean id="hello" class="spring.Hello1" >
    <property name="message" value
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值