Reputation: 7226
How does Spring know when to call 'destory' method on a session/request scoped bean (in other words, how does it detect that the concerned bean is going out of scope)?
I read somewhere that it uses request/session listeners to be notified of these events. But these listners need to be defined in web.xml, and there's no mention of defining such listeners in Spring literature. So how does this work?
Upvotes: 7
Views: 5627
Reputation: 983
You can implement the interface DisposableBean
and InitializingBean
for session scoped bean.
The org.springframework.beans.factory.InitializingBean
interface allows a bean to perform initialization work after all necessary properties on the bean have been set by the container. The InitializingBean interface specifies a single method afterPropertiesSet()
.
Implementing the org.springframework.beans.factory.DisposableBean
interface allows a bean to get a callback when the container containing it is destroyed. The DisposableBean interface specifies a single method destroy()
.
Read more about it here: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-nature
Upvotes: 1
Reputation: 28951
The org.springframework.web.servlet.DispatcherServlet
does it. It uses own code, e.g. the org.springframework.web.context.request.RequestAttributes#registerDestructionCallback
callback list functionality to register all these scoped beans.
Upvotes: 2
Reputation: 340708
and there's no mention of defining such listeners in Spring literature
Oh, there is:
To support the scoping of beans at the
request
,session
, and global session levels (web-scoped beans), some minor initial configuration is required before you define your beans.[...]If you use a Servlet 2.4+ web container, [...] you need to add the following
javax.servlet.ServletRequestListener
to the declarations in your web applications web.xml file[...]
From: 4.5.4.1 Initial web configuration.
Also note that Spring does not call destroy on prototype
-scoped beans.
Upvotes: 2