Friday, 28 August 2015

Singleton beans scopes in Spring

Beans with different Id’s have Singleton instance

singleton: (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

NO, Similar beans with different ids make the different instance (Even scope is defined as Singleton); because the singleton scope checked on the basis of bean ids.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

       default-autowire="byName" default-autowire-candidates="*">

       <context:annotation-config />

       <bean id="id1" class="spring.core.singleton.Singleton">
              <property name="name" value="Rajesh kumar"></property>

       <bean id="id2" class="spring.core.singleton.Singleton">
              <property name="name" value="Awadh kumar"></property>

package spring.core.singleton;
public class Singleton {
       private String name;

       public String getName() {
              return name;

       public void setName(String name) {
     = name;

package spring.core.singleton;
import org.springframework.context.ApplicationContext;

public class TestSingletonScope {
       public static void main(String[] args) {

              ApplicationContext appContext = new ClassPathXmlApplicationContext
              Singleton singleton1 = appContext.getBean("id1", Singleton.class);
              Singleton singleton2 = appContext.getBean("id2", Singleton.class);

              if(singleton1==singleton2) {
              } else {
                     System.out.println("not singleton");

Rajesh kumar
Awadh kumar
not singleton

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...