Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring session-scoped beans (controllers) and references to services, in terms of serialization

  • a standard case - you have a controller (@Controller) with @Scope("session").
  • classes put in the session usually are expected to implement Serializable so that they can be stored physically in case the server is restarted, for example
  • If the controller implements Serializable, this means all services (other spring beans) it is referring will also be serialized. They are often proxies, with references to transaction mangers, entity manager factories, etc.
  • It is not unlikely that some service, or even controller, hold a reference to the ApplicationContext, by implementing ApplicationContextAware, so this can effectively mean that the whole context is serialized. And given that it holds many connections - i.e. things that are not serializable by idea, it will be restored in corrupt state.

So far I've mostly ignored these issues. Recently I thought of declaring all my spring dependencies transient and getting them back in readResolve() by the static utility classes WebApplicationContextUtils and such that hold the request/ServletContext in a ThreadLocal. This is tedious, but it guarantees that, when the object is deserialized, its dependencies will be "up to date" with the current application context.

Is there any accepted practice for this, or any guidelines for serializing parts of the spring context.

Note that in JSF, managed beans (~controllers) are stateful (unlike action-based web frameworks). So perhaps my question stands more for JSF, than for spring-mvc.

like image 676
Bozho Avatar asked Jul 05 '10 16:07

Bozho


1 Answers

In this presentation (around 1:14) the speaker says that this issue is resolved in spring 3.0 by providing a proxy of non-serializable beans, which obtains an instance from the current application context (on deserialization)

like image 150
Hans Westerbeek Avatar answered Sep 30 '22 20:09

Hans Westerbeek