Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a bean-post processor that call destroy methods on prototypes?

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?

like image 315
Pasha Avatar asked Oct 14 '25 16:10

Pasha


1 Answers

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();
    }
}
like image 191
Todd Avatar answered Oct 17 '25 05:10

Todd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!