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.
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.
- Spring Tutorials ( Collection for Spring reference documentations)
- Spring Framework Interview Questions
- Email Integration in Spring Framework
- Introduction to Spring REST Services
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"?>
2<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3xmlns="http://java.sun.com/xml/ns/javaee"
4xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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
1<beans xmlns="http://www.springframework.org/schema/beans"
2 xmlns:context="http://www.springframework.org/schema/context"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:mvc="http://www.springframework.org/schema/mvc"
5 xmlns:aop="http://www.springframework.org/schema/aop"
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
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:
1 | com.javabeat.beans |
2 | com.javabeat.controller and |
3 | com.javabeat.impl |
1 | package com.javabeat.beans; |
2 |
3 | public interface HelloRequestScopeData { |
4 | public String getDate(); |
5 | } |
1 | package com.javabeat.beans; |
2 |
3 | public interface HelloSessionScopeData { |
4 | public String getDate(); |
5 | } |
1 | package com.javabeat.impl; |
2 |
3 | import java.util.Date; |
4 | import com.javabeat.beans.HelloRequestScopeData; |
5 |
6 | public 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 | } |
1 | package com.javabeat.impl; |
2 |
3 | import java.util.Date; |
4 | import com.javabeat.beans.HelloSessionScopeData; |
5 |
6 | public 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 | } |
1 | package com.javabeat.controller; |
2 |
3 | import org.springframework.beans.factory.annotation.Autowired; |
4 | import org.springframework.stereotype.Controller; |
5 | import org.springframework.ui.Model; |
6 | import org.springframework.web.bind.annotation.RequestMapping; |
7 |
8 | import com.javabeat.beans.HelloRequestScopeData; |
9 | import com.javabeat.beans.HelloSessionScopeData; |
10 |
11 | @Controller |
12 | public 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 | } |
1 | <?xml version="1.0" encoding="UTF-8"?> |
2 | <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
3 | xmlns="http://java.sun.com/xml/ns/javaee" |
4 | xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" |
5 | xsi:schemaLocation="http://java.sun.com/xml/ns/javaee |
6 |
7 | http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" |
8 |
9 | id="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> |
1 | <beans xmlns="http://www.springframework.org/schema/beans" |
2 | xmlns:context="http://www.springframework.org/schema/context" |
3 | xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
4 | xmlns:mvc="http://www.springframework.org/schema/mvc" |
5 | xmlns:aop="http://www.springframework.org/schema/aop" |
6 | xsi:schemaLocation=" |
7 |
8 | http://www.springframework.org/schema/beans |
9 |
10 |
11 | http://www.springframework.org/schema/beans/spring-beans-3.0.xsd |
12 |
13 |
14 | http://www.springframework.org/schema/context |
15 |
16 |
17 | http://www.springframework.org/schema/context/spring-context-3.0.xsd |
18 |
19 |
20 | http://www.springframework.org/schema/aop |
21 |
22 |
23 | http://www.springframework.org/schema/aop/spring-aop-3.0.xsd |
24 |
25 |
26 | http://www.springframework.org/schema/mvc |
27 |
28 |
29 | http://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> |
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> |
0 komentar:
Posting Komentar