Bean 生命周期

Spring 执行流程

Spring 执⾏流程:

  1. 启动 Spring 容器

  2. 读取配置,扫描路径(找注解)

  3. 实例化 Bean(分配内存空间)

  4. Bean 注册到 Spring 中(存入IoC容器中)

  5. 将 Bean 装配到需要的类中(对象装配、依赖注入)

Bean 生命周期

  1. 实例化(给Bean分配内存空间

  2. 设置属性(对象装配,给@Autowired修饰的属性赋值)

  3. Bean 初始化

    • 执行各种 Aware 通知的方法,如 BeanNameAware、BeanFactoryAware、ApplicationContextAware 的接口方法。
    • 执行初始化前置方法。
    • 执行 @PostConstruct 初始化方法。(@PostConstruct 注解修饰)
    • 执行自己指定的 init-method 方法。(使用 xml 方式存 Bean,同时可以指定初始化方法名)
    • 执行初始化后置方法。
  4. 使用 Bean

  5. 销毁 Bean

    • 容器销毁时,执行Bean的各种销毁⽅法,如 DisposableBean 接⼝⽅法、@PreDestroy 注解方法、destroy-method XML方法。

为什么设置属性在初始化之前?

因为初始化操作可能会用到注入的对象。

在这里插入图片描述

Bean生命周期代码演示

BeanLifeTest 类:

public class BeanLifeTest implements BeanNameAware {
    @Override
    public void setBeanName(String s) {
        System.out.println("执行 BeanNameAware 通知:" + s);
    }
    public BeanLifeTest() {
        System.out.println("执行构造方法");
    }
    @PostConstruct
    public void doPostConstruct() {
        System.out.println("@PostConstruct 初始化方法");
    }
    @PreDestroy
    public void doDestroy() {
        System.out.println("@PreDestroy 销毁方法");
    }
    public void myInit() {
        System.out.println("init-method 初始化方法");
    }
    public void myDestroy() {
        System.out.println("destroy-method 销毁方法");
    }
}
  • 实现了 BeanNameAware 接口的通知方法。

config.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:content="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 https://www.springframework.org/schema/context/spring-context.xsd">
    <content:component-scan base-package="test"></content:component-scan>
    <bean id="myBean" class="test.BeanLifeTest" init-method="myInit" destroy-method="myDestroy"></bean>
</beans>
  • 使用配置文件的方式注册Bean,可以设置 init-method 初始化方法和 destroy-method 销毁方法。

启动类:

public class App {
    public static void main(String[] args) {
		
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
        // 销毁 Spring 上下文,
        context.destroy();
    }
}
  • 使用 Application 的子类 ClassPathXmlApplicationContext,因为 Application 没有 destroy 方法。

运行结果:

在这里插入图片描述

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值