Spring MVC - Using Session Scoped Beans

[Last Updated: Apr 4, 2018]

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

To understand how to use session scope object, let's see an 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.

Registering a bean with session scope

public class MyWebConfig {

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

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

Injecting the session bean

We are going to 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";

JSP page


<%@ page language="java"
    contentType="text/html; charset=ISO-8859-1"
<%@taglib prefix="c" uri=""%>
<h2>Trades </h2>
   <h3> Message : ${msg} <h3>
<h4>Current visitor history</h4>
<p>ip : ${visitor.ip}:</p>
<c:forEach items="${visitor.pagesVisited}" var="page">


How it works?

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

The returned 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.


To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

The outputs shows that all visited urls are added to a single instance of our Visitor object, hence it is kept in the HttpSession object.

Other ways to handle session attributes

  • Using @SessionAttributes (example here).
  • Using HttpSession as a controller method argument (next tutorial).

Example Project

Dependencies and Technologies Used:

  • Spring Web MVC 5.0.5.RELEASE: Spring Web MVC.
  • Spring TestContext Framework 5.0.5.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.3.9

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

    See Also