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.

 

click the next for more ...
Hacker Leaked Celebrities Naked Photos and  Gets 8 Months check the story!
Hacker Leaked Celebrities Naked Photos and Gets 8 Months check the story!
Hacker Leaked Celebrities Naked Photos and  Gets 8 Months check the story!

.
SCANDAL FaceBook FINED Cambridge for 500 000  £
SCANDAL FaceBook FINED Cambridge for 500 000 £

Facebook has finally been weaking up with its first fine of £500,000 for Cambridge Analytica to improperly gather and misapply data of 87 m


SCANDAL FaceBook FINED Cambridge for 500 000  £
Marvel Comics Giant Stan Lee Has Died At 95

Stan Lee, the colorful Marvel Comics patriarch who helped usher in a new era of superhero storytelling -- and saw his creations become a giant influen


SCANDAL FaceBook FINED Cambridge for 500 000  £
How Does Android s New In-app Updates API Work

Notice that the Android§apostrofe§s new In-app Updates API doesn§apostrofe§t force or lock out users from the app if they chose no


SCANDAL FaceBook FINED Cambridge for 500 000  £
Capitan has slept in the grave of his owner every night

For the past 6 years, a dog named Capitan has slept in the grave of his owner every night. His owner, Miguel Guzman died in 2006 and Capitan dissapear


SCANDAL FaceBook FINED Cambridge for 500 000  £
Kendall Jenner Has Been A Granted Permanent Restraining Order Against Her Alleged Stalker

Kendall Jenner§apostrofe§s supposed stalker was requested to avoid the supermodel for a long time on Friday subsequent to being gotten on her proper


SCANDAL FaceBook FINED Cambridge for 500 000  £
So Your Dog Has Canine Cancer Here s What to do Next

One in four dogs will be diagnosed with canine cancer in their lifetime, and cancer is the second leading cause of death in older animals. That’



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