InitializingBean and DisposableBean in Spring

Spring InitializingBean and DisposableBean are the interfaces used in life cycle of Spring beans management. Each of these interfaces has only one method. InitializingBean has a method called afterPropertiesSet() and DisposableBean has a method called destroy().

Spring container runs the method afterPropertiesSet() once the bean properties have been set and Spring container runs destroy() method once Spring container releases the bean.

You can also use init and destroy methods or @PostConstruct and @PreDestroy annotations to perform the similar jobs.

Now let’s move to create an example on how these interfaces are used in Spring application.

We create a class that implements InitializingBean and DisposableBean interfaces.

package com.roytuts.spring.initializingbean.disposablebean;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

@Component
public class InitializingDisposableBean implements InitializingBean, DisposableBean {

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("Do some initialization stuffs");
	}

	@Override
	public void destroy() throws Exception {
		System.out.println("Do some clean up stuffs");
	}

}

Create a Java configuration class to scan the Spring beans annotated with @Component, @Service, etc. from classpath.

package com.roytuts.spring.initializingbean.disposablebean;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.roytuts.spring.initializingbean.disposablebean")
public class Config {

}

Now we will create a main class to test our application.

package com.roytuts.spring.initializingbean.disposablebean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class InitializingDisposableBeanApp {

	public static void main(String[] args) {
		ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);

		InitializingDisposableBean idb = context.getBean(InitializingDisposableBean.class);

		System.out.println(idb);

		((ConfigurableApplicationContext) context).close();
	}

}

The above main class will give you the following output:

Do some initialization stuffs
com.roytuts.sp[email protected]498d318c
Do some clean up stuffs

Source Code

Download

Thanks for reading.

Related posts

Leave a Comment