spring bean的建立與消亡由spring容器進行管理,除了使用<bean><property/></bean>進行簡單的屬性配置以外,spring支持更人性化的方法spring
1 public class BeanInitMethod implements InitializingBean, DisposableBean { 2 3 private int step; 4 5 public int getStep() { 6 return step; 7 } 8 9 public void setStep(int step) { 10 this.step = step; 11 } 12 13 @PostConstruct 14 public void postConstruct() { 15 System.out.println("initialized by annotation"); 16 step = 1; 17 } 18 19 @PreDestroy 20 public void predestroy() { 21 System.out.println("destroyed by annotation"); 22 } 23 24 @Override 25 public void afterPropertiesSet() throws Exception { 26 System.out.println("initialized by interface"); 27 step = 2; 28 } 29 30 @Override 31 public void destroy() throws Exception { 32 System.out.println("destroyed by interface"); 33 } 34 35 public void initFunc() { 36 System.out.println("initialized by xml"); 37 step = 3; 38 } 39 40 public void destroyFunc() { 41 System.out.println("destroyed by xml"); 42 } 43 44 public static void main(String[] argv) { 45 BeanInitMethod beanInitMethod; 46 BeanFactory beanFactory = new ClassPathXmlApplicationContext("applicationContext.xml"); 47 beanInitMethod = (BeanInitMethod) beanFactory.getBean("initTestBean"); 48 49 System.out.println("step=" + beanInitMethod.getStep()); 50 51 System.out.println("program is done"); 52 } 53 54 }
對於「註解方式」還須要開啓註解的支持,在上下文xml配置文件加入app
<context:annotation-config/>
對於xml配置方式,則須要加入ide
<bean id="initTestBean" class="edu.xhyzjiji.cn.spring.BeanInitMethod" init-method="initFunc" destroy-method="destroyFunc"/>
當bean實例被建立時,會依據如下順序執行初始化post
initialized by annotation initialized by interface initialized by xml step=3 program is done