Session Scoped Beans in Spring

If your Spring application context is associated with a Java EE container (eg: created via ), you can set your bean in a session scope. This means every user starting a new http session will obtain a different copy of your bean.

Let’s see this in action. Below I have a ShoppingCart bean

public class ShoppingCart implements Serializable {
  private int userId;
  private List products;
  // getters & setters ...
}

Configure this to be a session scoped bean in spring xml configuration file:


  

The tag will cause Spring to create a proxy class over the ShoppingCart bean. This is critical because we want to inject our ShoppingCart to a singleton class (eg: Service / Controller classes) yet each user’s http session should get its own copy of the data.

In order for proxying to take effect you also need to include cglib library into your classpath.

I can now inject the ShoppingCart into HomeController:


("/home")
public class HomeController {

   private ShoppingCart shoppingCart;

  ...
}

One way to think about this is the proxy is actually a singleton mirror image of the ShoppingCart class, except each user coming from different HttpSession will see different data when they invoke the public methods. For each new HttpSession, on the first time user invokes one of the proxied method a new actual ShoppingCart bean instance is created behind the screen.

Leave a Reply