Spring bean scopes (Request, Session, Global Session) with example

When you define a bean in the configuration file, you are just defining the structure of the bean or it is just a class. With that definition, you can create any number of instances. Here the advantage of the bean is that, you are not only allowed to define the dependencies for the beans, you also can set the scope for the beans. The spring framework supports following five scopes. Out of which three scopes are supported only in web ApplicationContext.

  • Singleton
  • Prototype
  • Request
  • Session
  • Global Session

  • I’ve already covered Singleton and Prototype in the post “Spring bean with examples”. Now let’s see an example of how to use Request and Session scopes.

    Note:Request, Session and Global Session scopes are valid in the context of a web-aware Spring ApplicationContext. This means that you can only use these scoped beans in a an application deployed to a web server. Spring can be used in applications that run in standard JVMs along with applications that run in servlet containers (Tomcat, etc). Request, Session and Global session however, only exists in web servers so it has no meaning if the application is running in a standard desktop environment.

    If you use these scopes with regular Spring IoC containers such as the ClassPathXmlApplicationContext, you get an IllegalStateException complaining about an unknown bean scope.

    also read: follow us on @twitter and @facebook

    Request and Session Scope Example

    Request scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext. Session scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
    Step 1: Create Project
    Let us have working Eclipse IDE in place. Create a Dynamic Web Project with a name Spring-Req-Session-scope-Eg. Follow the option File -> New -> Project ->Dynamic Web Project and finally select Dynamic Web Project wizard from the wizard list. Now name your project as Spring-Req-Session-scope-Eg using the wizard window.
    Step 2: Add external libraries
    Drag and drop below mentioned Spring and other libraries into the folder WebContent/WEB-INF/lib:
    • antlr-2.7.2.jar
    • aopalliance-1.0.jar
    • org.springframework.web.servlet-3.2.2.RELEASE.jar
    • spring-aop-3.2.2.RELEASE.jar
    • spring-aspects-3.2.2.RELEASE.jar
    • spring-beans-3.2.2.RELEASE.jar
    • spring-context-support-3.2.2.RELEASE.jar
    • spring-context-3.2.2.RELEASE.jar
    • spring-core-3.2.2.RELEASE.jar
    • spring-expression-3.2.2.RELEASE.jar
    • commons-logging-1.1.1.jar
    • spring-web-3.2.2.RELEASE.jar
    Step 3: Create bean and Controller
    Create the following packages under src folder. (Right click onsrc -> New -> Package -> package-name)
    1com.javabeat.beans
    2com.javabeat.controller and
    3com.javabeat.impl
    Create the the bean files com\javabeat\beans\HelloRequestScopeData.java (for request scope) and com\javabeat\beans\HelloSessionScopeData.java (for session scope). These beans are wired into a basic Spring MVC application. Contents of these files are as below:
    HelloRequestScopeData.java
    1package com.javabeat.beans;
    2 
    3public interface HelloRequestScopeData {
    4    public String getDate();
    5}
    HelloSessionScopeData.java
    1package com.javabeat.beans;
    2 
    3public interface HelloSessionScopeData {
    4    public String getDate();
    5}
    Create the bean implementation file com\javabeat\impl\HelloRequestScopeDataImpl.java and com\javabeat\impl\HelloSessionScopeDataImpl.java. Contents of these files are as below:
    HelloRequestScopeDataImpl.java
    1package com.javabeat.impl;
    2 
    3import java.util.Date;
    4import com.javabeat.beans.HelloRequestScopeData;
    5 
    6public class HelloRequestScopeDataImpl implements HelloRequestScopeData {
    7 
    8    private final Date date;
    9 
    10    public HelloRequestScopeDataImpl(Date date) {
    11        this.date = date;
    12    }
    13 
    14    @Override
    15    public String getDate() {
    16        return date.toString();
    17    }
    18}
    HelloSessionScopeDataImpl.java
    1package com.javabeat.impl;
    2 
    3import java.util.Date;
    4import com.javabeat.beans.HelloSessionScopeData;
    5 
    6public class HelloSessionScopeDataImpl implements HelloSessionScopeData {
    7    private final Date date;
    8 
    9    public HelloSessionScopeDataImpl(Date date) {
    10        this.date = date;
    11    }
    12 
    13    @Override
    14    public String getDate() {
    15        return date.toString();
    16    }
    17}
    Create the controller com\javabeat\controller\HelloController.java, the contents are as below:
    HelloController.java
    1package com.javabeat.controller;
    2 
    3import org.springframework.beans.factory.annotation.Autowired;
    4import org.springframework.stereotype.Controller;
    5import org.springframework.ui.Model;
    6import org.springframework.web.bind.annotation.RequestMapping;
    7 
    8import com.javabeat.beans.HelloRequestScopeData;
    9import com.javabeat.beans.HelloSessionScopeData;
    10 
    11@Controller
    12public class HelloController {
    13 
    14    @Autowired
    15    private HelloRequestScopeData requestscopehellodata;
    16 
    17    @Autowired
    18    private HelloSessionScopeData sessionscopehellodata;
    19 
    20    @RequestMapping(value = "/")
    21    public String hellodata(Model model) {
    22        model.addAttribute("requestscopedate", requestscopehellodata.getDate());
    23        model.addAttribute("sessionscopedate", sessionscopehellodata.getDate());
    24 
    25        /* return to view "hello.jsp" */
    26        return "hello";
    27    }
    28}
    This controller has a dependency of type HelloRequestScopeData and HelloSessionScopeData. We display the date from bean in both requets and session scope. The veiw is returned to “hello.jsp”.
    Note:  In the above example@Autowired annotation will search for the matching type in the spring beans and automatically wire the   suitable bean instance to the object. You need not declare any other explicit mentioning of the injecting the objects, @Autowired is most powerful annotation to decide the suitable object. @RequestMapping is the context path definition for the request. This annotation maps all the matching request from that path will be send to this particular controller method. For more details please read spring mvc tutorials.
    Step 4: Create Configuration files
    web.xml
    1<?xml version="1.0" encoding="UTF-8"?>
    5xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    6 
    7http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    8 
    9id="WebApp_ID" version="2.5">
    10  <display-name>Spring-Req-Session-scope-Eg</display-name>
    11  <servlet>
    12    <servlet-name>HelloWeb</servlet-name>
    13    <servlet-class>
    14         org.springframework.web.servlet.DispatcherServlet
    15      </servlet-class>
    16    <load-on-startup>1</load-on-startup>
    17  </servlet>
    18  <servlet-mapping>
    19    <servlet-name>HelloWeb</servlet-name>
    20    <url-pattern>/</url-pattern>
    21  </servlet-mapping>
    22  <listener>
    23    <listener-class>
    24        org.springframework.web.context.request.RequestContextListener
    25    </listener-class>
    26  </listener>
    27</web-app>
    HelloWeb-servlet.xml
    6   xsi:schemaLocation="
    7 
    8http://www.springframework.org/schema/beans
    9 
    10 
    11http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    12 
    13 
    14http://www.springframework.org/schema/context
    15 
    16 
    17http://www.springframework.org/schema/context/spring-context-3.0.xsd
    18 
    19 
    20http://www.springframework.org/schema/aop
    21 
    22 
    23http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    24 
    25 
    26http://www.springframework.org/schema/mvc
    27 
    28 
    29http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    30 
    31 <mvc:annotation-driven />
    32<bean
    33  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    34  <property name="prefix" value="/WEB-INF/jsp/" />
    35  <property name="suffix" value=".jsp" />
    36</bean>
    37 
    38<context:component-scan base-package="com.javabeat" />
    39<context:annotation-config />
    40<bean id="requestscope" class="com.javabeat.impl.HelloRequestScopeDataImpl" scope="request">
    41  <constructor-arg>
    42    <bean class="java.util.Date" />
    43  </constructor-arg>
    44   <aop:scoped-proxy proxy-target-class="false" />
    45</bean>
    46<bean id="sessionscope" class="com.javabeat.impl.HelloSessionScopeDataImpl" scope="session">
    47  <constructor-arg>
    48    <bean class="java.util.Date" />
    49  </constructor-arg>
    50   <aop:scoped-proxy proxy-target-class="false" />
    51</bean>
    52</beans>
    Here two beans are defined one has “request” (for bean HelloRequestScopeDataImpl) scope and other “session” (for bean HelloSessionScopeDataImpl) scope. The request scope tells Spring to instantiate a new HelloRequestScopeDataImpl bean with each Web request, and to make that bean available only within the context of that Web request. The session scope tells Spring to instantiate a new HelloSessionScopeDataImpl bean with each Web session, and to make that bean available only within the context of that Web session.
    The <aop:scoped-proxy /> element tells Spring that this bean is not to be injected as a dependency directly, but instead an AOP proxy of this bean is to be injected in its place. The proxy-target-class=”false” attribute tells Spring not to use a CGLIB proxy, but a JDK dynamic proxy instead.
    A simple view displays the Date, one which is created for each request the controller receives and one is for each session. The contents of the file are as below:
    hello.jsp
    1<%@page language="java" contentType="text/html; charset=ISO-8859-1"
    2    pageEncoding="ISO-8859-1"%>
    3<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    5<html>
    6<head>
    7<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    8<title>Hello World</title>
    9</head>
    10<body>
    11   <h2>---Request Scope Date----</h2>
    12   <h2>${requestscopedate}</h2>
    13   <h2>---------------------------</h2>
    14   <h2>---Session Scope Date----</h2>
    15   <h2>${sessionscopedate}</h2>
    16   <h2>---------------------------</h2>
    17</body>
    18</html>
    Step 5: Deploy and Execute
    The final structure of the project is as show below:
    Final dir_structure_req scope
    Step 6: Output
    Now start your Tomcat server and make sure you are able to access other web pages from webapps folder using a standard browser. Now try to access the URL http://localhost:8080/spring/ and if everything is fine with your Spring Web Application, you should see the following result:
    output

    Global Session Scope

    The global session scope is similar to the Session scope and really only makes sense in the context of portlet-based web applications. The portlet specification defines the notion of a global Session that is shared among all of the various portlets that make up a single portlet web application. Beans defined at the global session scope are bound to the lifetime of the global portlet Session.

    Summary

    In my earlier post I have explained about “Spring bean with examples”. In this post we saw an example of how to use the scopes Request and Session. My next post shall cover creating custom scope for Spring beans. If you have any questions on scopes, please write it on the comments section. If you are interested in receiving the future articles, please subscribe here.


    SHARE

    Milan Tomic

    Hi. I’m Designer of Blog Magic. I’m CEO/Founder of ThemeXpose. I’m Creative Art Director, Web Designer, UI/UX Designer, Interaction Designer, Industrial Designer, Web Developer, Business Enthusiast, StartUp Enthusiast, Speaker, Writer and Photographer. Inspired to make things looks better.

    • Image
    • Image
    • Image
    • Image
    • Image
      Blogger Comment
      Facebook Comment

    0 komentar:

    Posting Komentar

    luvne.com ayeey.com cicicookies.com mbepp.com tipscantiknya.com kumpulanrumusnya.comnya.com