004——Spring中Bean的初始化和销毁

Bean的初始化有三种方法:

  • 通过 元素的 init-method/destroy-method属性指定初始化之后 /销毁之前调用的操作方法
  • 如果在上下文中定义的很多Bean都拥有相同名字的初始化方法和销毁方法,使用元素的default-init-method/default-destroy-method
  • 通过实现InitializingBean/DisposableBean 接口来定制初始化之后/销毁之前的操作方法
package com.java.spring;

public class InitAndDestroy {

	public void init() {
		System.out.println("bean was born");
	}
	
	public void destroy() {
		System.out.println("bean was dead");
	}
	
	public void coming() {
		System.out.println("|I am coming");
	}
}

package com.java.spring;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class InitDestroy implements InitializingBean, DisposableBean {

	public void afterPropertiesSet() throws Exception {
		System.out.println("InitDestroy was born");
	}

	public void destroy() throws Exception {
		System.out.println("InitDestroy was dead");
	}

	public void coming() {
		System.out.println("I am coming");
	}
}
测试类:
package com.java.spring;

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

public class Practice {

	public static void main(String[] args) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		InitDestroy id = (InitDestroy) ctx.getBean("InitDestroy");
		id.coming();
		((ClassPathXmlApplicationContext) ctx).close();//关闭应用上下文容器
	}
	
}
配置文件:



       
      
      
        
           




你可能感兴趣的:(Spring)