Caching current user data in a session-scoped variable

2.5k Views Asked by At

How can I cache a current User instance for the duration of an entire user session, so that my services can access it freely without having to go to the user access services and then fetch the user data from the database over and over again.

I know that Spring supports the concept of scoped beans (per session, per request, etc), but honestly speaking, I have never actually used it, so I would be very thankful if someone could show me the way.

I am highly hopeful that this sort of session scoping is thread safe.

2

There are 2 best solutions below

10
On

Spring is not the solution for everything. HttpSession is what you need. And session scoping is not thread-safe.

0
On

If you use Spring Security, then you may consider to use an enhanced UsersDetails object.

-- You only (because you only know your usecases) have to decide if this is usefull.


To answer your Question about Session Scoped Spring Objects:

See Spring Reference Chapter 3.11.4.4 Specifying bean scope for an example, and Chapter 3.4. Bean scopes for an overview of scopes (attention the link to Session within that chapter is wrong).

And notice that Spring Session Scoped Beans requires that listener:

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

IHO: It depends on what you will do with that session scoped data, whether you should use Spring Session Beans or the HTTP Session directly. For example if you need that data in different places within the service layer, then the HTTP Session may be a not so good solution.