Categories
Java

Using session scoped beans in Spring

Spring 2.0 added a wonderful scope to the “Singleton” and “Prototype” scopes – “Session”.
For every request, Spring will create an instance of a bean and bind it to that user throughout that user’s session. This is ideal because it keeps the HTTP-connectivity layer outside the realm of the service layer.

It was a bit of a sad moment when Spring told us to shove it when we assigned the session scope to one of our beans. The error looked like

cope 'session' is not active for the current thread; consider defining a scoped proxy for this bean
if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException

Some searching uncovered what else is needed to make session scope happen:
1. In web.xml, define a RequestContextListener, for example:

<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

2. In the body of the session scoped bean, add the following element:
<aop:scoped-proxy/>

Read more.

Share
Share