Spring MVC - Using Session Scoped backing Objects

[Updated: Feb 8, 2017, Created: Feb 21, 2016]

In the last tutorial we saw how to use @SessionAttributes along with @ModelAttribute to store session objects.

In this tutorial, we are going to see a cleaner alternative.

A backing object can be autowired/injected to a Spring MVC controller with predefined scopes. These scopes are 'request' and 'session' scopes.

To understand how to use session scope object, we are going to modify our last example.

To avoid narrower scope bean DI problem as we saw when injecting Prototype bean into a Singleton Bean, we will preferably use JSR 330 Provider approach. Here's a list of other solutions.

Let's see some code. We are going to take following two steps:

Register 'Visitor' object as a bean in our @Configuration class. We are going to specify the scope as 'session'

public class MyWebConfig {

    public TradeController tradeController () {
        return new TradeController();

    public Visitor visitor(HttpServletRequest request){
         return new Visitor(request.getRemoteAddr());

Inject our session bean wrapped in Provider interface:

public class TradeController {

    private Provider<Visitor> visitorProvider;

    public String handleRequestById (Model model, HttpServletRequest request) {
        model.addAttribute("msg", "trades request, serving page "
                                                     + request.getRequestURI());

        return "traders-page";

How it works?

The factory method of @Configuration class, MyWebConfig#visitor, is called at the beginning of each new HTTP session.

The return object from the factory method is stored in HTTPSession and is kept there till the session ends.

visitorProvider.get() returns the same instance for the same session.

Example Project

To test controllers run the unit tests in TradeControllerTest.

Or you can run the app using embedded tomcat:

mvn  clean install tomcat7:run-war

Use this URL in your browser :


/** can be replace with anything including long URI paths e.g. /trades/currentMonth/323/brokers

The outcome will the same as the last example

Dependencies and Technologies Used:

  • Spring Web MVC 4.2.4.RELEASE: Spring Web MVC.
  • Spring TestContext Framework 4.2.4.RELEASE: Spring TestContext Framework.
  • Java Servlet API 3.0.1
  • javax.servlet:jstl 1.2
  • javax.inject 1: The javax.inject API.
  • JUnit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • JDK 1.8
  • Maven 3.0.4

Spring Session Scope Example Select All Download
  • spring-session-scoped-object
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • WEB-INF
            • views
      • test
        • java
          • com
            • logicbig
              • example

See Also