Spring has an interface you can implement called DestructionAwareBeanPostProcessor. Instances of this interface are asked first if a bean needs destruction via the requiresDestruction()
method. If you return true, you will eventually get called back again with that bean when it is about to be destroyed via the postProcessBeforeDestruction
method.
What this does is it gives you a chance to clean up that bean's resources. For example if your bean has a reference to a File, you could close any streams you might have open. The important point is your class doesn't hold a reference to the bean that is about to be destroyed, or you'll hold it up from being garbage collected as you've pointed out.
To define a post-processor, you would do something like this
@Component
public class MyDestructionAwareBeanPostProcessor implements DestructionAwareBeanPostProcessor {
public boolean requiresDestruction(final Object bean) {
// Insert logic here
return bean instanceof MyResourceHolder;
}
public void postProcessBeforeDestruction(final Object bean, final String beanName) throws BeansException {
// Clean up bean here.
// Example:
((MyResourceHolder)bean).cleanup();
}
}