spring bean的生命周期

13 篇文章 0 订阅

spring bean的生命周期

名称: init-method, destroy-method

类型:属性

归属: bean标签

作用:定义bean对象在初始化或销段时完成的工作

格式:<bean init-methoda"init" destroy-method-"deatroy>

取值: bean对应的类中对应的具体方法名

 public class UserServiceImpl implements UserService {
UserServiceImpl (){
    System.out.println("镜音铃来啦");
}

    public void init(){
        System.out.println("初始化bean");
    }

    public void save() {
        System.out.println("洛天依,米库");
    }

    public void destory(){
        System.out.println("死亡bean");
    }
}

spring配置文件

<!--bean的scope属性-->
<bean id="userService" scope="singleton" init-method="init" destroy-method="destory" class="com.itheima.service.impl.UserServiceImpl"/>

init-method=“init” 意思是将init方法设置为初始化方法
destroy-method=“destory” 意思是将destory方法设置为销毁方法
他们后面的值 是方法的名称

控制台的显示信息
注意 scope=“singleton” 是单列的对象

初始化bean

spring配置文件

<!--bean的scope属性-->
<bean id="userService" scope="prototype" init-method="init" destroy-method="destory" class="com.itheima.service.impl.UserServiceImpl"/>

控制台的显示信息
注意 scope=“prototype” 是非单列的对象

镜音铃来啦
初始化bean
镜音铃来啦
初始化bean
镜音铃来啦
初始化bean

要运行销毁方法要用到ClassPathXmlApplicationContext 的close方法
但是 ApplicationContext对象是不能使用ClassPathXmlApplicationContext的close方法
所以要用ClassPathXmlApplicationContext对象来获取bean的class属性

   ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
     //获取资源
        UserService userService1 = (UserService)ctx.getBean("userService");
        UserService userService2 = (UserService)ctx.getBean("userService");
        UserService userService3 = (UserService)ctx.getBean("userService");

        ctx.close();

这样控制台输出的是
控制台的显示信息
注意 scope=“singleton” 是单列的对象
运行destroy方法

镜音铃来啦
初始化bean
死亡bean

控制台的显示信息
注意 scope=“prototype” 是非单列的对象
不运行destroy方法

镜音铃来啦
初始化bean
镜音铃来啦
初始化bean
镜音铃来啦
初始化bean

这是因为prototype 不归spring的容器管理,也就是非单列没有将对象放到spring的容器中,运行的结束是将spring容器给关闭,没有放在容器中也就不会在容器关闭是执行

注意事项:
1.当scope="singleton"时, spring容器中有且仅有一个对象, init方法在创建容器时仅执行一次

2.当scope="prototype"时, spring容器要创建同一类型的多个对象, init方法在每个对象创建时均执行一次

3.当scope="singleton"时,关闭容器会导致bean实例的销段,调用destroy方法一次

4.当scope="prototype"时,对象的销毁由垃圾回收机制gc0)控制, destroy方法将不会被执行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

普希托夫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值