Spring (init-method和destroy-method )

转自:http://www.blogjava.net/cmzy/archive/2008/07/29/218059.html

  1. /**
  2. *
  3. */
  4. packageioc.test;
  5. /**
  6. *@authorzhangyong
  7. *
  8. */
  9. publicclassAnimal{
  10. privateStringname;
  11. privateintage;
  12. publicStringspeak(){
  13. return"我的名字:"+this.name+",我的年龄:"+this.age;
  14. }
  15. publicvoidinit_xx()throwsException{
  16. System.out.println("初始化方法start()正在运行!");
  17. }
  18. publicvoidend()throwsException{
  19. System.out.println("析构方法end()正在运行!");
  20. }
  21. //Geter和Seter省略
  22. }

配置文件中配置好bean,并为其指定响应的预处理方法和析构方法:

这里的init_xx方法在实例化与依赖注入之前被调用,end方法在销毁之前调用

  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <beans
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  7. <beanid="animal"class="ioc.test.Animal"init-method="init_xx"destroy-method="end">
  8. <propertyname="age"value="5"></property>
  9. <propertyname="name"value="猪"></property>
  10. </bean>
  11. </beans>

创建含有主方法的测试类,代码如下:

  1. /**
  2. *
  3. */
  4. packageioc.test;
  5. importorg.springframework.context.support.AbstractApplicationContext;
  6. importorg.springframework.context.support.ClassPathXmlApplicationContext;
  7. /**
  8. *@authorzhangyong
  9. *
  10. */
  11. publicclassTestMain{
  12. publicstaticvoidmain(String[]args){
  13. AbstractApplicationContextac=newClassPathXmlApplicationContext("applicationContext.xml");
  14. //注册容器关闭钩子,才能关掉容器,调用析构方法
  15. ac.registerShutdownHook();
  16. Animalanimal=ac.getBean("animal",Animal.class);
  17. System.out.println(animal.speak());
  18. }
  19. }

运行主类,结果如下:


需要注意的是:要看到析构方法的输出,也必须要注册关闭钩子。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值