4

I'm reading Spring documentation and found this

One possible way to get the Spring container to release resources used by prototype-scoped beans is through the use of a custom bean post-processor which would hold a reference to the beans that need to be cleaned up.

But if bean-post processor holds a reference to the prototype object then Garbage Collector won't clean it and prototypes beans with their resources will reside in a heap until Application Context is close?

Could you clarify it, please?

Pasha
  • 1,768
  • 6
  • 22
  • 43

1 Answers1

5

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();
    }
}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Todd
  • 30,472
  • 11
  • 81
  • 89