Spring Bean Scope using Annotation – Singleton, Prototype, Request, Session, Global Session, Application

The tutorial shows you the way to implement Bean Scopes (Singleton, Prototype, Request and Session) using Annotation @Scope. Except Singleton and Prototype Scope, the others are only valid in the context of a web-aware Application.

Related Article: Spring Bean Scope – Singleton and Prototype

I. Technology

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

II. Overview
1. Goal

To build a simple application using @Scope annotation that shows you the way singleton, prototype, request, session act and the difference between them.
Beside, we also have a lean introduction of globalSession and application scope.

2. Project Structure

beanscope-annotation-structure
Customer class has four @Autowired members:
+ Name: singleton
+ Language: prototype
+ Address: request
+ Age: session
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
– 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

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

Click Next, in Web: choose Web:
springaop-aspectj-configweb

Click Finish. Spring Boot project will be created successfully.

2. Create Classes for Beans

We annotate the classes 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 don’t use globalSession and application scope.
Now, under package bean, create necessary classes.

Content of Name.java:

Content of Language.java:

Content of Address.java:

Content of Age.java:

Content of Customer.java:

3. Create a WebController

Under package controller, create class WebController.
Content of WebController.java:

4. Add configuration to application.properties

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

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:

After running project, we can see that system has the message:

This case occurs to singleton scope bean.

Request 1
http://localhost:8080/name
beanscope-annotation-req1

Request 1-1
http://localhost:8080/namecheck
beanscope-annotation-req12
Request 2
http://localhost:8080/language
beanscope-annotation-req2
System shows:

Request 2-1
http://localhost:8080/languagecheck
beanscope-annotation-req2-1
System shows:

Request 3
http://localhost:8080/address
beanscope-annotation-req3
System shows:

Request 3-1
http://localhost:8080/addresscheck
beanscope-annotation-req31
System shows:

Request 4
http://localhost:8080/age
beanscope-annotation-req4
System shows:

Request 4-1
http://localhost:8080/agecheck
beanscope-annotation-req41
System doens’t show anything more.

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

IV. Source Code

spring-beanscope-annotation

By JavaSampleApproach | September 8, 2016.

Last updated on June 4, 2017.


Related Posts


6 thoughts on “Spring Bean Scope using Annotation – Singleton, Prototype, Request, Session, Global Session, Application”

  1. If I am changing Name class scope to prototype and then given request to http://localhost:8080/name, it is calling Name class constructor 4 times. could you please let me know why it is happening?

    1. Hi Rahul Sahu,

      I’ve checked sourcecode again with “Name class scope to prototype“, and everything works normally (if you don’t set proxyMode = TARGET_CLASS)
      “calling Name class constructor 4 times” doesn’t happen.

      So please check your case again and give me more details.

      Regards,
      JSA.

      1. Hi JSA,

        Thanks for the reply.

        I had forget to add that I have add proxyMode = ScopedProxyMode.TARGET_CLASS also.
        like below

        Now when I am giving request to http://localhost:8080/name. it is calling Name class constructor 4 time.

        1. Hi Rahul Sahu,

          >> prototype: new instance is created everytime prototype bean is referenced.

          When you set proxyMode = ScopedProxyMode.TARGET_CLASS, you will invoke constructor method everytime you make reference to bean of this class:

          So, when you make request to http://localhost:8080/name, you will run 3 statements:

          1- String result = customer.getCustomerName();

          2- customer.setCustomerName(“Adam”, “Johnson”);

          3- return “init Data: ” + result + “|—–| modified Data: ” + customer.getCustomerName();

          You can see that bean name has been referenced 4 times, so it will call Name class constructor 4 times.

          Regards,
          JSA.

          1. Ohhhh, Thanks a lot for making me understand.
            but if it is creating new bean every time then what is the use of it?
            we can not use in real time application.

          2. Hi Rahul Sahu,

            For real world example of Prototype Scope, you can declare some configuration parameters for a form class (parameters to validate name, e-mail address…) and get “living” instances of them for every form being created.

            Consider using this kind of prototype when:
            1- There is a class that has many config parameters
            2- You need to create many instances of it with a set of predefined configuration
            3- You think that everytime you call it, you call a factory method that creates the instance of it.

            Regards,
            JSA.

Got Something To Say:

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

*