Spring Bean的生命周期

在bean中加入init-method , 和destory-method 

测试类:

关闭容器,执行销毁的方法。 

2.实现InitializingBean, DisposableBean接口

public class HelloSpring implements InitializingBean,DisposableBean {

    private String hello ;

    public HelloSpring() {
        System.out.println("构造对象了...");
    }

    public void setHello(String hello) {
        System.out.println("注入了一个Hello的属性..." + hello);
        this.hello = hello;
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("被卸载了...");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("属性设置之后调用...");
    }

    public void init() {
        System.out.println("init方法...");
    }

    public void disposable() {
        System.out.println("disposable方法");
    }
}
<bean name="helloSpring" class="com.csi.bean.HelloSpring" init-method="init" destroy-                
       method="disposable">
   <property name="hello" value="今天天气好晴朗" />
</bean>

测试类

package com.csi.bean;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestHelloSpring {

    @Test
    public void showHelloSpring() {
        //步骤1:需要先加载Spring核心配置文件
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml") ;
        //步骤2:需要获取到bean的id名称,也就是获取到由容器创建的对象
        HelloSpring helloSpring = (HelloSpring) ctx.getBean("helloSpring");
        System.out.println(helloSpring);

        //使用注册关闭钩子。在虚拟机退出之前回调此函数,关闭容器
        ctx.registerShutdownHook();

        //步骤3:输出结果
//        System.out.println(helloSpring);

    }

}

执行结果:

 先执行接口

Bean销毁时机

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值