MemeStorm

Exploring the Spring Framework and Application Development

Use Spring’s bean lifecycle callback methods to control your destiny

Posted in All by Jon on the February 19th, 2006

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 Print This Post

One Response to 'Use Spring’s bean lifecycle callback methods to control your destiny'

Subscribe to comments with RSS or TrackBack to 'Use Spring’s bean lifecycle callback methods to control your destiny'.

  1. kitty said,

    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

Leave a Reply