In general, two lifecycle events are particularly relevant to a bean: post-initialization and pre-destruction. Both of these lifecycle events are only fired for beans that are singletons.
1. post-initialization event. 2 ways to implement it: method-based and interface-based.
1) method based. Specify the init method name in the configuration file (init-method="method name").
- <bean id="simpleBean1"
- class="SimpleBean"
- init-method="init">
- <property name="age">
- <value>100value>
- property>
- bean>
2) interface based. Implement InitializingBean interface and define afterPropertiesSet() method.
- public class SimpleBeanWithInterface implements InitializingBean {
- public void afterPropertiesSet() throws Exception {
- System.out.println("Initializing bean");
- }
- }
2. pre-destruction event. 2 ways to implement it: method-based and interface-based.
1) method based. Specify the destroy mothod in the config file. (destroy-method="method name")
- <bean id="destructiveBean"
- class="DestructiveBean"
- destroy-method="destroy">
- <property name="filePath">
- <value>d:/tmp/test.txtvalue>
- property>
- bean>
2) interface based. Implement DisposableBean interface and define destroy() method.
- public class DestructiveBeanWithInterface implements DisposableBean {
- public void destroy() {
- System.out.println("Destroying Bean");
- }
- }
Destruction callbacks are not fired automatically. You need to remember to call destroySingletons() before the application is closed. When the application runs as a servlet, you can simple call the method in the servlet's destroy() method. However, in a stand-alone application, you need to take advantage of the Java's shutdown hook, a thread executed just before the application shuts down.
- public class ShutdownHook implements Runnable {
- private ConfigurableListableBeanFactory factory;
- public ShutdownHook(ConfigurableListableBeanFactory factory) {
- this.factory = factory;
- }
- public void run() {
- System.out.println("Destroying Singletons");
- factory.destroySingletons();
- System.out.println("Singletons Destroyed");
- }
- }
Register this Thread as a shutdown hook using Runtime.addShutdownHook().
- public class ShutdownHookExample {
- public static void main(String[] args) {
- ConfigurableListableBeanFactory factory = new XmlBeanFactory(
- new FileSystemResource(
- "./disposeInterface.xml"));
- Runtime.getRuntime().addShutdownHook(
- new Thread(new ShutdownHook(factory)));
- DestructiveBeanWithInterface bean =
- (DestructiveBeanWithInterface)factory.getBean("destructiveBean");
- }
- }
本文介绍Spring框架中Bean的两种主要生命周期事件:初始化后(post-initialization)及销毁前(pre-destruction)。文章详细解释了这两种事件的实现方式,包括基于方法和基于接口的方法,并提供了具体的XML配置示例和Java代码示例。
342

被折叠的 条评论
为什么被折叠?



