Searching...
Tuesday, 13 August 2013

Spring Disposable Bean Example

01:12

Disposable Bean is used to do some closing/destructive task before destroying bean. It is same destroy method in Bean life cycle Bean life cycle methods

Create a Java class

Create java class which implements Disposable Bean interface and implement destroy method. In this method we can add all our closing or destructive tasks

package com.pretech; 
importorg.springframework.beans.factory.DisposableBean; 
public class ClosingBean implements DisposableBean 
{
	public void destroy() {
		System.out.println("doing all close activities");
	}
}

Add bean details into spring configuration (SpringConfig.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-3.0.xsd ">
<beanid="dBean"class="com.pretech.ClosingBean"/>
</beans>

Create a main class to test DisposableBean

package com.pretech; 
importorg.springframework.context.support.AbstractApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext; 
public class DisposableBeanTest { 
	public static void main(String[] args) {
		AbstractApplicationContext context = newClassPathXmlApplicationContext("SpringConfig.xml");
		context.registerShutdownHook();
	} 
}

output



doing all close activities

0 comments: