InitializingBean 和 DisposableBean
init-method 和 destroy-method
@PostConstruct 和 @PreDestroy
In Spring, InitializingBean and DisposableBean are two marker interfaces, a useful way for Spring to perform certain actions upon bean initialization and destruction.
- For bean implemented InitializingBean, it will run
afterPropertiesSet()
after all bean properties have been set. - For bean implemented DisposableBean, it will run
destroy()
after Spring container is released the bean.
In Spring, you can use init-method and destroy-method as attribute in bean configuration file for bean to perform certain actions upon initialization and destruction.
Note
The @PostConstruct and @PreDestroy annotation are not belong to Spring, it’s located in the J2ee library – common-annotations.jar.
具体的使用
对于第一个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
下面的例子展示了 init-method and destroy-method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
第三种的使用:
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 |
|
By default, Spring will not aware of the @PostConstruct and @PreDestroy annotation. To enable it, you have to either register ‘CommonAnnotationBeanPostProcessor‘ or specify the ‘<context:annotation-config />‘ in bean configuration file,
1. CommonAnnotationBeanPostProcessor
1 2 3 4 5 6 7 8 9 10 11 12 |
|
2. <context:annotation-config />
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|