bean对象 生命周期

bean对象生命周期

在Spring中,Bean的生命周期包括Bean的定义、初始化、调用、销毁 4个阶段

bean初始化 方式一

  • 在bean标签配置 init-method属性 来指定初始化时调用的方法
public class TypeDao {
    //定义初始化时被调用的方法
    public void test1() {
        System.out.println("TypeDao...");
    }
}
  • xml配置文件 bean标签
<!--通过init-method属性指定初始化方法-->
<bean id="typeDao" class="com.zh.dao.TypeDao" scope="singleton" init-method="test1" lazy-init="true"/>

bean初始化 方式二

  • 实现 import org.springframework.beans.factory.InitializingBean 接口
public class TypeDao implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("实现 InitializingBean 初始化Bean ,重写afterPropertiesSet方法,初始化Bean");
    }
}

bean调用

  • BeanFactory 或 ApplicationContext
//得到spring上下文环境
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring04.xml");

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring04.xml");
  • ApplicationContext 接口间接继承 BeanFactory

在这里插入图片描述

bean销毁

  • bean标签添加 destroy-method 属性,指定销毁方法
<!--bean对象销毁方法 destroy-method-->
<bean id="typeDao" class="com.zh.dao.TypeDao" destroy-method="destroy"/>
  • 通过 AbstractApplicationContext 接口,close方法销毁bean对象
AbstractApplicationContext aac = new ClassPathXmlApplicationContext("spring04.xml");
aac.close();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值