An Interview Question on Spring


Nordnet Baritof
Nordnet Baritof
  • Technical Writer
  • Entrepreneur
  • Founder and CEO
  • Developer
  • Blogger and IT Analyst
2018-08-29 17:31:04

| Share
| Share
| Share
An Interview Question on Spring

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

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=[skipt]1.0[skipt] encoding=[skipt]UTF-8[skipt]?>
<beans xmlns=[skipt]http://www.springframework.org/schema/beans[skipt]
    xmlns:xsi=[skipt]http://www.w3.org/2001/XMLSchema-instance[skipt]
    xsi:schemaLocation=[skipt]http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd[skipt]>
    <bean id=[skipt]scopeTest[skipt] class=[skipt]com.example.scope.Scope[skipt] scope=[skipt]singleton[skipt]>
        <property name=[skipt]name[skipt] value=[skipt]Shamik Mitra[skipt]/>    
    </bean>    
    <bean id=[skipt]scopeTestDuplicate[skipt] class=[skipt]com.example.scope.Scope[skipt] scope=[skipt]singleton[skipt]>
        <property name=[skipt]name[skipt] value=[skipt]Samir Mitra[skipt]/>    
    </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 [skipt]Scope [name=[skipt] + name + [skipt]][skipt];
    }
}

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(
            [skipt]configFiles/Scope.xml[skipt]);
        Scope scope = (Scope) ctx.getBean([skipt]scopeTest[skipt]);
        Scope scopeDuplicate = (Scope) ctx.getBean([skipt]scopeTestDuplicate[skipt]);
        System.out.println(scope == scopeDuplicate);
        System.out.println(scope + [skipt]::[skipt] + 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.

 

Hacker Leaked Celebrities Naked Photos and  Gets 8 Months check the story!
Hacker Leaked Celebrities Naked Photos and Gets 8 Months check the story!
.
An Interview Question on Spring
An Interview Question on Spring

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


An Interview Question on Spring
TensorFlow 1.10 has just been released. Here’s what’s new.

Tensorflow, the popular Machine Learning framework, just released its version 1.10 on 09/08/2018. As any data scientist worthy of this name, ignoring


An Interview Question on Spring
7 best node js frameworks for developers

Node.JS is a platform built on V8, the Javascript engine which allows you to create fast and scalable web applications. Node.JS uses an event model an


An Interview Question on Spring
How to get from idea to prototype in 5 steps

The word 'prototype' has a long history. It derives ultimately from two ancient Greek words: photos (first) and typos (impression). It is impo


An Interview Question on Spring
6 differences between good designers and great designers

Great designers design in multiple mediums seamlessly They incorporate the whole user flow into the design - no matter where that takes them.


An Interview Question on Spring
8 tips for a happy development team

1. Start every meeting with good news No matter how good or bad your day, somebody somewhere is doing something great in your company. Take 30 seco



© 2013-2019 best of geeks. All rights reserved.