DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • The Best of Java Interview Questions
  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services

Trending

  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  • Building Enterprise-Ready Landing Zones: Beyond the Initial Setup
  • Streamlining Event Data in Event-Driven Ansible
  1. DZone
  2. Culture and Methodologies
  3. Career Development
  4. An Interview Question on Spring Singletons

An Interview Question on Spring Singletons

Spring Singletons are not Java Singletons. Let's go over the important differences between them and how Spring singletons interact within containers.

By 
Shamik Mitra user avatar
Shamik Mitra
·
Feb. 20, 17 · Tutorial
Likes (73)
Comment
Save
Tweet
Share
164.1K Views

Join the DZone community and get the full member experience.

Join For Free

While interviewing for positions using Spring Core, I often ask a certain question, "What do you mean by Spring Singleton scope?"

Most of the time, I get an answer like, "Spring Singleton scope manages only one object in the container."

After getting this answer, I ask the next question, "Please tell me what the output of the following program would be."

Spring.xml:

<?xml version="1.0" encoding="UTF-8"?>
<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="scopeTest" class="com.example.scope.Scope" scope="singleton">
        <property name="name" value="Shamik Mitra"/>    
    </bean>    
    <bean id="scopeTestDuplicate" class="com.example.scope.Scope" scope="singleton">
        <property name="name" value="Samir Mitra"/>    
    </bean>
</beans>


Scope.java:

package com.example.scope;
public class Scope {
    private String name;
    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Scope [name=" + name + "]";
    }
}


Main class:

package com.example.scope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext(
            "configFiles/Scope.xml");
        Scope scope = (Scope) ctx.getBean("scopeTest");
        Scope scopeDuplicate = (Scope) ctx.getBean("scopeTestDuplicate");
        System.out.println(scope == scopeDuplicate);
        System.out.println(scope + "::" + scopeDuplicate);
    }
}


Here, I create two beans of the Scope class and make Spring Scope a singleton, now checking the references.

This is where interviewees sometimes get confused. Usually, I will get three types of answers:

  • This code will not compile. It will throw an error at runtime, as you can not define two Sspring beans of the same class with Singleton Scope in XML. (Very rare)

  • The reference check will return true, as the container maintains one object. Both bean definitions will return the same object, so the memory location would be the same. (Often)

  • The reference check will return false, which means Spring Singletons don't work like they said earlier. (A few)

The third answer is the correct answer. A Spring Singleton does not work like a Java Singleton.

If we see the output of the program, we will understand that it will return two different instances, So in a container, there may be more than one object in spite of the fact that the Scope is the singleton.

Output:

Reference Check ::false
Scope [name=Shamik Mitra]::Scope [name=Samir Mitra]


So, let's ask the question again. "What do you mean by Spring Singleton Scope?"

According to the Spring documentation:

"When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.

To put it another way, when you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned."

So it is clear that for a given id, a Spring container maintains only one shared instance in a singleton cache.

In my example, I use two different ids (scopeTest and ScopeTestDuplicate), so the Spring container creates two instances of the same class and binds them with respective ids, then stores them in a Singleton cache.

You can think of a Spring container as managing a key-value pair, where the key is the id or name of the bean and the value is the bean itself. So, for a given key, it maintains a Singleton. So if we use that key as a reference to or of other beans, the same bean will be injected to those other beans.

In summation, Spring guarantees exactly one shared bean instance for the given id per IoC container, unlike Java Singletons, where the Singleton hardcodes the scope of an object such that one and only one instance of a particular class will ever be created per ClassLoader.

And we'll close on this picture taken from the Spring docs.

Spring Framework Interview (journalism)

Opinions expressed by DZone contributors are their own.

Related

  • The Best of Java Interview Questions
  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!