码迷,mamicode.com
首页 > 编程语言 > 详细

spring bean初始化和销毁

时间:2016-12-17 11:42:09      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:override   配置文件   public   string   one   ann   人性化   str   顺序   

spring bean的创建与消亡由spring容器进行管理,除了使用<bean><property/></bean>进行简单的属性配置之外,spring支持更人性化的方法

  • @PostConstruct @PreDestroy
  • xml的init-method和destroy-method
  • 实现InitializingBean和DisposableBean接口 
 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

 

spring bean初始化和销毁

标签:override   配置文件   public   string   one   ann   人性化   str   顺序   

原文地址:http://www.cnblogs.com/xhyzjiji/p/6188592.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!