对Spring Bean 生命周期方法的总结
1
2
3
4
| @Bean(initMethod = "initMethod", destroyMethod = "destroyMethod")
public BeanTest beanTest() {
return new BeanTest();
}
|
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
| import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
/**
* @author itning
* @date 2019/6/22 10:04
*/
public class BeanTest implements InitializingBean, DisposableBean, BeanPostProcessor, ApplicationContextAware {
public BeanTest() {
System.out.println("1.constructor");
}
@PostConstruct
public void postConstruct() {
System.out.println("2.PostConstruct");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("3.InitializingBean:afterPropertiesSet");
}
public void initMethod() {
System.out.println("4.initMethod");
}
@PreDestroy
public void annDestroy() {
System.out.println("1.PreDestroy");
}
@Override
public void destroy() throws Exception {
System.out.println("2.DisposableBean:destroy");
}
public void destroyMethod() {
System.out.println("3.destroyMethod");
}
/*@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization:" + beanName + " " + bean);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization:" + beanName + " " + bean);
return bean;
}*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
AnnotationConfigServletWebServerApplicationContext a = (AnnotationConfigServletWebServerApplicationContext) applicationContext;
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) a.getBeanFactory();
new Thread(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
beanFactory.removeBeanDefinition("beanTest");
}).start();
}
}
|
初始化:
- constructor
- PostConstruct
- InitializingBean:afterPropertiesSet
- initMethod
销毁:
- PreDestroy
- DisposableBean:destroy
- destroyMethod
文章作者
itning
上次更新
2019年06月22日 10:29:01
许可协议
CC BY-NC-ND 4.0