• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring Bean Scopes Example

December 23, 2015 by javainterviewpoint Leave a Comment

While defining Spring Bean we have options to define scopes for each bean. Spring supports 5 bean scopes.

  1. singleton – This scope returns a single bean instance per Spring IoC container(Default Scope)
  2. prototype – This scope returns a new bean instance every time
  3. request – This scope returns a single bean instance for each HTTP request.
  4. session – This scope returns a single bean instance for each HTTP session.
  5. globalSession – This scope returns a single bean instance for each global HTTP session.

Last three scopes (request, session, globalSession) can be used only with web-aware ApplicationContext.

We will learn a bit more about singleton and prototype scopes in this article

Folder Structure:

  1. Create a new Java Project  “SpringCoreTutorial” and create a package for our src files “com.javainterviewpoint“
  2. Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.

    commons-logging-1.1.1.jar
    spring-beans-3.2.9.RELEASE.jar
    spring-core-3.2.9.RELEASE.jar
    spring-context-3.2.9.RELEASE.jar
    spring-expression-3.2.9.RELEASE.jar

  3. Create the Java classes Book.java and ClientLogic.java under  com.javainterviewpoint folder.
  4. Place our configuration file SpringConfig.xml in the src directory

Book.java

Book class will have all the book details such title, author, publications and its corresponding POJO’s. The getBookDetails() method will display the book information which is set.

package com.javainterviewpoint;

public class Book 
{
    private String title;
    private String author;
    private String publications;
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public String getPublications() {
        return publications;
    }
    public void setPublications(String publications) {
        this.publications = publications;
    }
    public void getBookDetails(String book)
    {
        System.out.println("**Published "+book+" Details**");
        System.out.println("Book Title        : "+title);
        System.out.println("Book Author       : "+author);
        System.out.println("Book Publications : "+publications);
    }
}

ClientLogic.java

package com.javainterviewpoint;

import java.util.Iterator;
import java.util.Set;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class ClientLogic
{
    public static void main(String args[])
    {
        //Read the configuration file
        Resource resource = new ClassPathResource("SpringConfig.xml");
        //Read all the bean definition
        BeanFactory bf = new XmlBeanFactory(resource);
        
        //Get the book1 Instance
        Book book1 = (Book)bf.getBean("book");
        book1.setTitle("Core Spring");
        book1.setAuthor("Java Interview Point");
        book1.setPublications("JIP");
        //Printing book1 details
        book1.getBookDetails("book1");
        
        //Getting book2 instance
        Book book2 = (Book)bf.getBean("book");
      //Printing book2 details
        book2.getBookDetails("book2");
    }
}
  • Resource class reads our Configuration File(SpringConfig.xml)
  • BeanFactory class read all the bean definition mentioned in the config file.
  • Get the Book Class instance by calling the getBean() method over the bean factory(book1 and book2).
  • The String passed to getBean() method should be equivalent to the id defined in the SpringConfig.xml
  • We will be setting values to attributes using book1 instance and call getBookDetails() method with both book1 and book2 instances.

Singleton Scope

SpringConfig.xml

In our configuration file we have defined the scope as “singleton”

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="book" class="com.javainterviewpoint.Book" scope="singleton"></bean>
</beans>

Output :
When we run our ClientLogic class, we will be getting the below output

**Published book1 Details**
Book Title        : Core Spring
Book Author       : Java Interview Point
Book Publications : JIP
**Published book2 Details**
Book Title        : Core Spring
Book Author       : Java Interview Point
Book Publications : JIP

Even though we didn’t set values for book2 instance we will get the values which is set for book1, as singleton scope is single bean instance per Spring IoC container. It is something like static variable in java

Prototype Scope

SpringConfig.xml

We will define scope as “prototype” from Book bean

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="book" class="com.javainterviewpoint.Book" scope="prototype"></bean>
</beans>

Output :
When we run our ClientLogic class, we will be getting the below output

**Published book1 Details**
Book Title        : Core Spring
Book Author       : Java Interview Point
Book Publications : JIP
**Published book2 Details**
Book Title        : null
Book Author       : null
Book Publications : null

Here we got book2 details as null as we have used prototype scope, which creates new bean instance every time.

Other interesting articles which you may like …

  • Spring 3 Hello World Example
  • Spring 3 JavaConfig Example
  • Spring 3 @Import annotation with JavaConfig Example
  • Dependency Injection In Spring
  • Spring Dependency Injection – Setter Injection
  • Spring Setter Injection With Primitive data types
  • Spring Setter Injection With Objects
  • Spring Dependency Injection With List Collection Example
  • Spring Dependency Injection With Set Collection Example
  • Spring Dependency Injection With Map Collection Example
  • Spring Dependency Injection With Properties Example
  • Spring Dependency Injection – Constructor Injection
  • Spring Difference between Setter and Constructor Injection

Filed Under: J2EE, Java, Spring, Spring Core, Spring Tutorial Tagged With: Bean Scopes, prototype, Singleton, Spring, Spring Bean Scopes

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·