Spring 初始化Init和销毁Destory:

    spring 容器对象的生命周期:
        1、spring 容器创建对象
        2、执行 init-method 方法
        3、调用自己的方法
        4、关闭 spring 容器时,执行 destroy-method 方法。



示例代码:

1、建 HelloWorld.java

            public class HelloWorld {
                public HelloWorld(){
                    System.out.println("new instance ------");
                }
                public  void  init(){    // 方法名任意
                    s.o.p("init")
                }
                public  void  destroy(){    // 方法名任意
                    s.o.p("destroy")
                }
                public void hello(){
                    System.out.println("hello");
                }
            }

2、applicationContext-initdestroy.xml 中添加属性 init-method 和 destroy-method

	<bean  id="helloInitDestroy"    class="cn.google.spring.initdestroy.HelloWorld"
			init-method="init"  destroy-method="destroy"></bean>
3、测试方法:

		public  class  InitDestroyTest{
			@Test
			public  void  testInitDestroy(){
				ApplicationContext  context = new ClassPathXmlApplicationContext("applicationContext.xml");
				HelloWorld   helloWorld = (HelloWorld) context.getBean("helloInitDestroy");
				helloWorld.hello();

				ClassPathXmlApplicationContext  app  = (ClassPathXmlApplicationContext)context;
				app.close();
			}
		}

        结果:new instance
                   init
                   hello
                   destroy

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值