Knowledge Walls
J2EE Technologies Tutorial
Hyderabad, Andhra Pradesh, India
Spring MVC request scoped bean with Example
request level scope of beans are initiate the instance each and every request calls. In below Example explained how to use request level beans in Spring.
Step.1 Start a Web based Spring application 
  1. Select New menu -> Dynamic Web Project
  2. Enter Project Name as "RequestScopeExample"
  3. Click Next, Selecting Target runtime as Apache Tomcat 7.0
  4. Click Next, Check Generate web.xml deployment descriptor then click on "Finish"
  5. Copy and paste Spring's 21 Framework Jars, aopalliance-1.0.jar, aspectjtools-1.6.6.jar and commons-logging-1.1.jar into /WEB-INF/lib
Step.2 Project Explorer Preview 
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi=""

  <!-- Dispatcher servlet for running beans-servlet.xml and request under bs/* pattern url's -->
package com.knowledgewalls;

public class RndHolder {
    private int rndNumber;
    public int getRndNumber(){
        return rndNumber;
    public void setRndNumber(int rndNumber){
        this.rndNumber = rndNumber;
    public void generateRndNumber(){
        this.rndNumber = (int) (Math.random() * 99999);
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <bean id="rndHolder" class="com.knowledgewalls.RndHolder" scope="request">
    <context:component-scan base-package="com.knowledgewalls"></context:component-scan>

package com.knowledgewalls;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

public class ShowAccountDetails extends HttpServlet {

    RndHolder rndHolder;
    public @ResponseBody void getMethod(HttpServletRequest request,HttpServletResponse response) throws Exception{
        response.getWriter().write("Old No. "+rndHolder.getRndNumber()+"\n");
        response.getWriter().write("New No. "+rndHolder.getRndNumber()+"\n");
        response.getWriter().write("Hash code Ref. "+rndHolder);
Not retain rnd number of last request. each request reference of the rndNumber object get Changed.
Running url: http://localhost:8089/RequestScopeExample/conn/ShowAccountDetails

Output: 1
Old No. 0
New No. 17632
Hash code Ref. com.knowledgewalls.RndHolder@17d2f0e

Output: 2
Old No. 0
New No. 61931
Hash code Ref. com.knowledgewalls.RndHolder@145c761
Best Lessons of "Spring 3.0 Examples"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details