Saturday, October 08, 2011

3 ways to initialize and destroy Spring beans

There are 3 ways to initialize (and destroy) spring beans
1. Using init-method and destroy-method attributes
2. Implementing InitializingBean and DisposableBean interfaces
3. Using @PostConstruct and @PreDestroy Annotations (available only in Spring >=2.5)


1. Using init-method and destroy-method attributes
Certain bean methods can designated as initializing and destroying methods using the init-method and destroy-method attributes. Like so:



<bean
    id="studentService"
    class="initMethod.StudentServiceImpl"
    init-method="subscribe"
    destroy-method="unsubscribe"/>



2. Implementing InitializingBean and DisposableBean interfaces
The bean can implement these methods InitializingBean.afterPropertiesSet() and DisposableBean.destroy(). Like so:

public class StudentServiceImpl implements StudentService, InitializingBean, DisposableBean {
    @Override
    public boolean isExists(long studentId) {
        // A fake implementation
        if ( studentId % 2 == 0 )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception 
    {
        // subscribe logic goes here
    }

    @Override
    public void destroy() throws Exception 
    {
       // unsubscribe logic goes here
    }
}



3. Using @PostConstruct and @PreDestroy Annotations
Note that both of these are JSR-250 annotations (here is a nice introduction to JSR-250 support introduced in spring 2.5).

@PostConstruct
public void subscribe()
{
  // subscribe logic goes here
}


@PreDestroy
public void unsubscribe()
{
  // unsubscribe logic goes here
}