Spring Bean Scope Annotation: @RequestScope | @SessionScope | @ApplicationScope

Spring Framework new release 4.3 make some Web Improvements. Among that, it simplifies way to implement Bean Scopes (Request, Session and Application scopes) using Annotation: @RequestScope | @SessionScope | @ApplicationScope. They are only valid in the context of a web-aware Application.

Related Articles:
Spring Bean Scope – Singleton and Prototype
Spring Bean Scope using Annotation – Singleton, Prototype, Request, Session, Global Session, Application

I. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.1.RELEASE

II. Overview
1. Goal

To build a simple application using @RequestScope and @SessionScope annotation that shows you the way request, session act and the difference between them.
Beside, we also have a lean introduction of @ApplicationScope.

2. Scope Annotation

With old approach, we usually annotate the class which bean has scope by:

@Scope(value = [scope], proxyMode = ScopedProxyMode.TARGET_CLASS)

– Proxy Mode TARGET_CLASS: is used for creating AOP proxy of the bean. We must do it when injecting short lived bean scope (request, session…) to long lived bean scope (singleton, prototype) or injecting prototype to singleton scope.
– We have some type of scope:
+ singleton: only one instance is created (default scope)
+ prototype: new instance is created everytime prototype bean is referenced.
+ request: one instance for a single HTTP request.
+ session: one instance for an HTTP Session
+ globalSession: one instance for a global HTTP Session. Typically only valid when used in a Portlet context.
+ application: Scopes a single bean definition to the lifecycle of a ServletContext (Only valid in the context of a web-aware Spring ApplicationContext).

In this tutorial, we only create example with request and session scope.
Our way is to use new scope annotations:
a- @RequestScope
@RequestScope is a annotation that acts as a shortcut for @Scope("request") with the proxyMode set to TARGET_CLASS.

b- @SessionScope
@SessionScope is a annotation that acts as a shortcut for @Scope("session") with the proxyMode set to TARGET_CLASS.

c- @ApplicationScope
@ApplicationScope is a annotation that acts as a shortcut for @Scope("application") with the proxyMode set to TARGET_CLASS.

3. Project Structure


Customer class has 2 @Autowired members:
+ Address: request scope
+ Age: session scope
WebController is a @RestController which has some request mappings to test data for each scope.
application.properties contains configuration for session cookie and timeout (in case of example for session scope).

3. Step to do

– Create Spring Boot project and add Dependency
– Create Classes for Beans
– Create a WebController
– Add configuration to application.properties
– Run Spring Boot Application & Enjoy Result

III. Practice
1. Create Spring Boot project and add Dependency

– Open Spring Tool Suite, on Menu, choose File -> New -> Spring Starter Project, then fill each fields:

– Click Next, then Finish. Spring Boot project will be created successfully.
– Add dependency to pom.xml:

		
			org.springframework.boot
			spring-boot-starter-web
		
2. Create Classes for Beans

Under package bean, create necessary classes:

Address.java:

package com.javasampleapproach.scopeannotation.bean;

import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.RequestScope;

@RequestScope
@Component
public class Address {
	
	private String address = "US";

	public Address() {
		System.out.println("Create new Address: " + this.address);
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}
}

Age.java:

package com.javasampleapproach.scopeannotation.bean;

import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.SessionScope;

@SessionScope
@Component
public class Age {
	
	private String age = "24";

	public Age() {
		System.out.println("Create new Age: " + this.age);
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}
}

Customer.java:

package com.javasampleapproach.scopeannotation.bean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Customer {

	private String name;

	@Autowired
	private Age age;

	@Autowired
	private Address address;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAge() {
		return age.getAge();
	}

	public void setAge(String age) {
		this.age.setAge(age);
	}

	public String getAddress() {
		return address.getAddress();
	}

	public void setAddress(String address) {
		this.address.setAddress(address);
	}
}
3. Create a WebController

Under package controller, create WebController class:

package com.javasampleapproach.scopeannotation.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.javasampleapproach.scopeannotation.bean.Customer;

@RestController
public class WebController {

	@Autowired
	private Customer customer;

	@RequestMapping("/address")
	public String address() {
		String result = customer.getAddress();
		customer.setAddress("EU");
		return "init Data: " + result + "|-----| modified Data: " + customer.getAddress();
	}

	@RequestMapping("/addresscheck")
	public String addresscheck() {
		return "check Data: " + customer.getAddress();
	}

	@RequestMapping("/age")
	public String age() {
		String result = customer.getAge();
		customer.setAge("25");
		return "init Data: " + result + "|-----| modified Data: " + customer.getAge();
	}

	@RequestMapping("/agecheck")
	public String agecheck() {
		return "check Data: " + customer.getAge();
	}
}
4. Add configuration to application.properties

Open application.properties under src/main/resources, add configuration:

server.session.cookie.max-age= 10
server.session.timeout= 10 

We set session timeout every 10 seconds to check the case of session scope.

5. Run Spring Boot Application & Enjoy Result

– Config maven build:
clean install
– Run project with mode Spring Boot App
– Check results:

Request 1
http://localhost:8080/address
System shows:

Create new Address: US

Web Browser:

Request 1-1
http://localhost:8080/addresscheck
System shows:

Create new Address: US

Web Browser:

Request 2
http://localhost:8080/age
System shows:

Create new Age: 24

Web Browser:

Request 2-1
http://localhost:8080/agecheck
System doens’t show anything more.
Web Browser:

Wait more than 10 seconds (timeout)
Request 2-2
http://localhost:8080/agecheck
System shows:

Create new Age: 24

Web Browser:

IV. Source Code

Spring-ScopeAnnotation



By grokonez | February 27, 2017.

Last updated on June 4, 2017.



Related Posts


3 thoughts on “Spring Bean Scope Annotation: @RequestScope | @SessionScope | @ApplicationScope”

  1. Why is there no Scope for the Customer? Don’t we have to use the @RequestScope or @SessionScope for the Customer?

    1. Hi Dan,

      It depends on your purpose, this tutorial just gives you an example that uses these annotations and shows how they work.
      If you want only one instance of Customer class for an HTTP Session, just use @SessionScope for it.

      Best Regards,
      JSA.

  2. Why is there no example for the ApplicationScope, if I want to count or store information about logged users, how can achieve this?

Got Something To Say:

Your email address will not be published. Required fields are marked *

*