title: Singleton in Java and Spring
body: <p>In simple words Singleton in Java means only one instance of a class in <em>JVM</em>. Whereas in Spring it is one instance of a class in the <em>Spring container</em> (reason is, single JVM can contain multiple Spring Container).</p>
  
  <p>In Java, when we implement a Singleton class we ensure that <strong>every-time the one and only</strong> instance of the class be returned, whenever accessed. This can be achieved by the below program.</p>
  
  <pre><code>public final class MySingleton {
  
      private static MySingleton mySingleton = new MySingleton();
  
      private MySingleton() {
      }
  
      public static MySingleton getInstance() {
          return mySingleton;
      }
  }
  </code></pre>
  
  <p>In case of spring if we define two beans of the same class we get two instance in our Java application when those beans are accessed.</p>
  
  <pre><code>&lt;bean id="employee1" class="test.demo.Employee" scope="singleton"&gt;&lt;/bean&gt;
  &lt;bean id="employee2" class="test.demo.Employee" scope="singleton"&gt;&lt;/bean&gt;
  </code></pre>
  
  <p>It is true that, <code>context.getBean("employee2");</code> always returns the same instance. At the same time, the default scope in Spring is Singleton. My question is, doesn't the above code defies the purpose of Singleton? </p>
  
  <p>Even if we define <code>scope="singleton"</code> in multiple bean declaration of the same class why does Spring always return a new instance?</p>