According to Spring documentation when a bean is scoped as "prototype" spring does not manage the complete lifecycle of its objects. More specifically the destruction lifecycle callbacks are not called. The client code must do the required clean ups. The spring documentation also suggests to use a custom bean post-processor for this purpose. But the "BeanPostProcessor" interface only includes callback methods for before and after initialization of beans. There is no method for desctruction callback. Then where and how to release resources obtained by prototype-scoped beans?
Therefore it's usually not necessary to explicitly destroy a prototype bean. However, in the case where a memory leak may occur as described above, prototype beans can be destroyed by creating a singleton bean post-processor whose destruction method explicitly calls the destruction hooks of your prototype beans.
In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance.
Lookup Method Injection Thus if you dependency-inject a prototype-scoped bean into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean. The prototype instance is the sole instance that is ever supplied to the singleton-scoped bean.
The destroy() method will be called before the bean is removed from the container. destroy-method is bean attribute using which we can assign a custom bean method that will be called just before the bean is destroyed.
What you're looking for is the DestructionAwareBeanPostProcessor, it's a sub-interface of BeanPostProcessor.
You could create a new implementation of that interface yourself, or use one of its implementing classes, like CommonAnnotationBeanProcessor.
The only clean way to terminate prototype-scoped bean is to explicitly call some of its "destroy"-methods to dispose resources. You can also use Phantom References. Here is more info on different types of references.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With