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

独自空忆成欢 提交于 2019-12-06 07:59:27

问题


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 :)


回答1:


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



来源:https://stackoverflow.com/questions/2809773/spring-beans-destroy-method-attribute-and-web-application-prototyped-bean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!