DisposableBean Interface and InitializingBean in Spring


 

DisposableBean Interface and InitializingBean in Spring

In this tutorial you will learn about Disposable Bean Interface and Initializing Bean of Spring framework.

In this tutorial you will learn about Disposable Bean Interface and Initializing Bean of Spring framework.

DisposableBean Interface and InitializingBean in Spring

The InitializingBean and DisposableBean are two marker interfaces which call the  afterPropertiesSet() for the begining and destroy() for the last action of initialization and    destruction to be performed.

StudentService.java

package com.roseindia.student.services;

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

public class StudentService implements InitializingBean, DisposableBean {
	String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public void afterPropertiesSet() throws Exception {
		System.out.println(" After properties has been set : " + message);
	}

	public void destroy() throws Exception {
		System.out.println("Cleaned everything!!");
	}

}

AppMain.java

package com.roseindia.common;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.roseindia.student.services.StudentService;

public class AppMain {
	public static void main(String[] args) {
		ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "context.xml" });
		StudentService stud = (StudentService) context
				.getBean("studentService");
		System.out.println(stud);
		context.close();
	}
}

context.xml

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

  <bean id="studentService" class="com.roseindia.student.services.StudentService">
    <property name="message" value="property message" />
  </bean>

</beans>

When you run this application it will display message as shown below:


After properties has been set : property message
com.roseindia.student.services.StudentService@80fa6f
.....
Cleaned everything!!

Download this example code

Ads