Spring (init-method和destroy-method )

系统 1981 0

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

  1. /**
  2. *
  3. */
  4. package ioc.test;
  5. /**
  6. *@authorzhangyong
  7. *
  8. */
  9. public class Animal{
  10. private Stringname;
  11. private int age;
  12. public Stringspeak(){
  13. return "我的名字:" + this .name+ ",我的年龄:" + this .age;
  14. }
  15. public void init_xx() throws Exception{
  16. System.out.println( "初始化方法start()正在运行!" );
  17. }
  18. public void end() throws Exception{
  19. System.out.println( "析构方法end()正在运行!" );
  20. }
  21. //Geter和Seter省略
  22. }

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

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

  1. <? xml version = "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. < bean id = "animal" class = "ioc.test.Animal" init-method = "init_xx" destroy-method = "end" >
  8. < property name = "age" value = "5" > </ property >
  9. < property name = "name" value = "猪" > </ property >
  10. </ bean >
  11. </ beans >

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

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

运行主类,结果如下:


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

Spring (init-method和destroy-method )


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论