Spring call to destroy method in beans / session scope

How does Spring know when to call the "destory" method in an area bound to a session / request bean (in other words, how does it detect that the corresponding bean is out of scope)?

I read somewhere that it uses request / session listeners to notify of these events. But these participants must be defined in web.xml, and there is no mention of the definition of such listeners in the Spring literature. So how does it work?

+4
source share
3 answers

org.springframework.web.servlet.DispatcherServlet does this. It uses native code, for example. org.springframework.web.context.request.RequestAttributes#registerDestructionCallback callback list function to register all of these beans areas.

+2
source

and there is no mention of the definition of such listeners in the Spring literature

Oh, there is:

To maintain the scope of beans at request , session and global session levels (beans web scope), some lower initial configuration is required before beans are defined. [...]

If you use the Servlet 2.4+ web container, [...] you need to add the following javax.servlet.ServletRequestListener to the ads in your web applications file web.xml [...]

From: 4.5.4.1 Initial web configuration .

Also note that Spring does not invoke destroy on prototype -scoped beans.

+2
source

You can implement the DisposableBean and InitializingBean interface for a bean session.

The org.springframework.beans.factory.InitializingBean interface allows the bean to perform initialization work after all the necessary properties on the bean have been set by the container. The InitializingBean interface specifies a single afterPropertiesSet() method.

The implementation of the org.springframework.beans.factory.DisposableBean interface allows the bean to receive a callback when the container containing it is destroyed. The DisposableBean interface defines one destroy() method.

Read more about this here: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-nature

+1
source

Source: https://habr.com/ru/post/1394980/


All Articles