Spring中控制Bean生命周期的三种方式

@PostConstruct & @PreDestroy InitializingBean & DisposableBean init-method & destory-method
执行顺序 最先 中间 最后
组件耦合度 与 JSR 规范耦合 与 SpringFramework 耦合 无侵入(只有 <bean>@Bean 中使用)
容器支持 注解原生支持,xml需开启注解驱动 xml 、注解原生支持 xml 、注解原生支持
单实例Bean
原型Bean 只支持 init-method

Pen

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Pen implements InitializingBean, DisposableBean {

public void initMethod() {
System.out.println("initMethod...");
}

public void destoryMethod() {
System.out.println("destoryMethod...");
}

@PostConstruct
public void postConstruct() {
System.out.println("postConstruct...");
}

@PreDestroy
public void preDestroy() {
System.out.println("preDestroy...");
}

@Override
public void destroy() throws Exception {
System.out.println("disposableBean");
}

@Override
public void afterPropertiesSet() throws Exception {
System.out.println("initializingBean");
}
}

LifecycleConfiguration

1
2
3
4
5
6
7
public class LifecycleConfiguration {

@Bean(initMethod = "initMethod",destroyMethod = "destoryMethod")
public Pen pen(){
return new Pen();
}
}

LifecycleApplication

1
2
3
4
5
6
7
public class LifecycleApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(LifecycleConfiguration.class);
applicationContext.getBean(Pen.class);
applicationContext.close();
}
}

输出

1
2
3
4
5
6
postConstruct...
initializingBean
initMethod...
preDestroy...
disposableBean
destoryMethod...