Thursday, November 6, 2008

Spring Session Scoped Bean

I have always hated direct usages of "HttpSession". You know how tricky it becomes when you want to do advanced things like session replications / caching etc. I have previously used home grown session factory abstraction. But just recently I came across Spring "Session Scoped Bean". So far, we have only used dependency injection of spring beans which had only 2 scopes - singleton & prototype. But now spring supports custom scopes for beans and one of them is "Session". It means that this bean is created when a new HttpSession is created and preserved as long as the HttpSession is valid. Spring uses AOP to extract the sessionId from the httprequest and manage the lifecycle of the bean. So instead of putting your object directly into the session, you get to put them in an injected POJO based placeholder. This makes it easy to do the testing and getting rid of HttpSession dependency. So when time comes, you can use solutions like "terracotta" to distribute your session without changing your code! Isn't that wonderful! Another niche Spring trick!

The details of how to setup the configurations can be found here. I followed the exact steps and it worked flawlessly.

2 comments:

salvin said...

Link is broken,

Please if possible provide the actual link or a better alternative,

I am dying to know how to use the session scoped bean in spring.

Pieter De Decker said...

You can dig up the original article with the Internet Wayback Machine. I should note however that things may have changed since Spring 2.0. (I wouldn't know, because I'm still learning Spring Web too.)

http://replay.web.archive.org/20080828160606/http://www.memestorm.com/blog/session-scoped-beans-in-spring-20/