标签:override 配置文件 public string one ann 人性化 str 顺序
spring bean的创建与消亡由spring容器进行管理,除了使用<bean><property/></bean>进行简单的属性配置之外,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配置文件加入
<context:annotation-config/>
对于xml配置方式,则需要加入
<bean id="initTestBean" class="edu.xhyzjiji.cn.spring.BeanInitMethod" init-method="initFunc" destroy-method="destroyFunc"/>
当bean实例被创建时,会依据以下顺序执行初始化
initialized by annotation initialized by interface initialized by xml step=3 program is done
标签:override 配置文件 public string one ann 人性化 str 顺序
原文地址:http://www.cnblogs.com/xhyzjiji/p/6188592.html