Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: How to cleanly terminate prototype-scoped beans?

Tags:

java

spring

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?

like image 288
Raihan Avatar asked Nov 16 '11 16:11

Raihan


People also ask

How do you destroy prototype beans in Spring?

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.

Why Spring does not call destroy method for prototype scoped 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.

What happens when a prototype bean is injected in singleton Bean?

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.

What is Bean destroy method?

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.


2 Answers

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.

like image 144
Derek Troy-West Avatar answered Oct 05 '22 12:10

Derek Troy-West


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.

like image 39
szhem Avatar answered Oct 05 '22 11:10

szhem