callback is often used in conjunction with the initialization callback. In many cases, you create and
configure a resource in the initialization callback and then release the resource in the destruction
callback.
Executing a Method When a Bean Is Destroyed
To designate a method to be called when a bean is destroyed, you simply specify the name of the method
in the destroy-method attribute of the bean's <bean> tag. Spring calls it just before it destroys the singleton
instance of the bean (as stated before, Spring will not call this method for those beans with prototype
scope). Listing 5-6 shows a simple class that implements InitializingBean, and in the
afterPropertiesSet() method, it creates an instance of FileInputStream and stores this in a private field.
Listing 5-6. Using a destroy-method Callback
package com.apress.prospring3.ch5.lifecycle;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.support.GenericXmlApplicationContext;
public class DestructiveBean implements InitializingBean {
private InputStream is = null;
public String filePath = null;
public void afterPropertiesSet() throws Exception {
System.out.println("Initializing Bean");
if (filePath == null) {
throw new IllegalArgumentException(
"You must specify the filePath property of " + DestructiveBean.class);
}
is = new FileInputStream(filePath);
}
public void destroy() {
System.out.println("Destroying Bean");
if (is != null) {
try {
is.close();
is = null;
} catch (IOException ex) {
System.err.println("WARN: An IOException occured"
+ " trying to close the InputStream");
}
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home