Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring bean's DESTROY-METHOD attribute and web-application "prototype"d bean

Can get work the attribute "destroy-method".

First, even if I type non-existing method name into "destroy-method" attribute,

Spring initialization completes fine (already strange!).

Next, when a bean has a "prototype" scope, then I suppose it must be destroyed before the application

is closed. That not happens, it is simply never called in my case.

Though, after extracting this bean I can call this method explicitly and it does its job.

Could you explain why this method is never called in my Spring 2.5 case?

p.s. The method exists, it is public and has no arguments.

It seems to be a more difficult task then I thought.

The problem is that this destroy method is called whenever the context is closed, and this is a rare case.

My question is this:

I have a web app. I have a "prototype"-scoped bean.

What I need is when the current session is closed, this destroy method was automatically called by Spring.

I can do it by hand, but is there any solution how to make Spring do this job? It destroys the bean after the session is destroyed, it might be possible for Spring to call a method on that bean before destroying it?

p.s. Spring does not manage the lifecycle of prototype beans, so Spring does not destroy them :)

like image 900
EugeneP Avatar asked Jan 22 '23 02:01

EugeneP


1 Answers

The Spring container doesn't manage prototype beans.

A snippet from the reference documentation:

Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called.

If possible, try the request or session scope.

When the HTTP Session is eventually discarded, the bean that is scoped to that particular HTTP Session is also discarded.

Btw: The session and request scope only works if you're using a web-aware ApplicationContext such as XmlWebApplicationContext

like image 71
Espen Avatar answered Feb 08 '23 12:02

Espen