Session Scoped Beans in Spring

If your Spring application context is associated with a Java EE container (eg: created via DispatcherServlet), 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<Product> products;
  // getters & setters ...
}

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

<bean class="com.gerrydevstory.ShoppingCart" scope="session">
  <aop:scoped-proxy/>
</bean>

The <aop:scoped-proxy/> 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:

@Controller
@RequestMapping("/home")
public class HomeController {

  @Autowired 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.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s