Spring Bean Life Cycle

The Spring Framework provides several callback interfaces to change the behavior of your bean in the container which includes InitializingBean and DisposableBean. The container calls afterPropertiesSet() and destroy() method to perform certain actions upon initialization and destruction.

Initialization callbacks

Implementing the org.springframework.beans.factory.InitializingBean interface allows a bean to perform initialization work after all necessary properties on the bean have been set by the container. It specifies a single method:

void afterPropertiesSet() throws Exception;

Click Here for source code.

As an alternative, you can also use init-method as attribute in bean configuration file for bean to perform certain actions upon initialization.

<bean id="employee" class="com.kruders.bean.Employee" init-method="init"> 

Click Here for source code.

There is one more way of doing same thing using @PostConstruct annotation.

@PostConstruct
public void init() throws Exception {
    System.out.println("Init method called: ");
}

Click Here for source code.

Destruction callbacks

Implementing the org.springframework.beans.factory.DisposableBean interface allows a bean to get a
callback when the container containing the bean is destroyed. It specifies a single method:

void destroy() throws Exception;

Click Here for source code.

As an alternative, you can also use destroy-method as attribute in bean configuration file for bean to perform certain actions upon destruction.

<bean id="employee" class="com.kruders.bean.Employee" destroy-method="destroy"> 

Click Here for source code.

There is one more way of doing same thing using @PreDestroy annotation.

@PreDestroy
public void destroy() throws Exception {
    System.out.println("Destroy method called: ");
}

Click Here for source code.

No comments yet.

Leave a Reply