Spring_07_init-method与destroy-method

需求

在创建bean对象后,调用一个初始化方法完成bean的初始化工作。

在Spring正常销毁前,调用一个结束/销毁方法做一些清理工作。

 

配置<bean>的init-method和destroy-method属性

· 默认情况下,在对应属性下,分别配置初始化方法名和结束方法名即可。

BeanObject

public class BeanObject implements IBeanObject {

    public BeanObject(){
        System.out.println("new BeanObject");
    }

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

    public void close(){
        System.out.println("beanObject close ...");
    }
}

配置文件

 <bean id="beanObject" class="com.hanaii.init_close.BeanObject"
          init-method="init" destroy-method="close"/>

测试代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class InitCloseTest {
   @Autowired
    private ApplicationContext ctx;

    @Test
    public void test(){
        BeanObject bean = ctx.getBean("beanObject", BeanObject.class);
    }
}

测试结果

 

· bean对象为原型模式时,Spring不会调用结束方法

配置文件

<bean id="beanObject" class="com.hanaii.init_close.BeanObject" scope="prototype"
    init-method="init" destroy-method="close"/>

测试结果

补充:bean对象为原型模式时,在手动启动时,即使正确关闭了容器,也不会调用结束方法。

 

· 手动启动容器时,必须要正常关闭Spring,Spring才能调用结束方法。

容器类型为:AbstractApplicationContext

通过调用容器对象的registerShutdownHook方法,在JVM的正常关闭线程中,添加一个Spring的关闭子线程。

只要JVM正常关闭,Spring就可正常关闭。

(可阅读该方法源代码,了解守护进程。)

测试代码

public class InitCloseTest {

    @Test
    public void test(){
        AbstractApplicationContext ctx = new ClassPathXmlApplicationContext
                ("com/hanaii/init_close/InitCloseTest-context.xml");
        BeanObject bean = ctx.getBean("beanObject", BeanObject.class);
        ctx.registerShutdownHook();
    }
}

测试结果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值