Use Spring’s bean lifecycle callback methods to control your destiny
You want to run an initialize or destroy method on a bean after the context creates it. These lifecycle methods allow you to grab and release resources.
How to do it
Well, we did this in the previous blog entry, making use of an ApplicationListener and InitializingBean. This was overkill! There’s a better way that doesn’t require these interfaces. To have a method execute after the bean is initialized, or just before it’s destroyed (ie. at context start up or shutdown), simply modify your configuration file as follows:
<bean id="databaseUtils" class="com.memestorm.utils.db.HSQLDB" init-method=”initialize” destroy-method=”destroy”> </bean>
You can of course omit either one, or both, of these attributes. The values of the attributes indicate the method that should be invoked. So for example, given the above definition the initialize() and destroy() method of the HSQLDB object will be invoked. This is great, and avoids any dependence on Spring interfaces.
If you’d like the same functionality relying on interfaces instead, then simply have the class implement InitializingBean and DisposableBean instead. In this case the configuration file will not have a init-method or destory-method attribute.
Print This Post
on June 13th, 2007 at 4:49 am
Hi,
Great info..Does this mean the beans are not destroyed when we give the scope = prototype ? Also , what is the difference between dispose and destroying a bean in spring ?
Thanks,
Kitty