Announcement Announcement Module
Collapse
No announcement yet.
What does Singleton really mean? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • What does Singleton really mean?

    Hello All,

    My understanding until now has been that Spring always created Singleton bean instances unless singleton="false" was specified.
    But here is what I did.

    <bean id="abstractRef" class="com.uhg.ut.uhc.spring.experiments.AbstractD emoImpl">
    <lookup-method name="getHelper" bean="helperRef"/>
    </bean>

    <bean id="abstractRef1" class="com.uhg.ut.uhc.spring.experiments.AbstractD emoImpl">
    <lookup-method name="getHelper" bean="helperRef"/>
    </bean>

    and then later in my code...

    Demo abstractBean = (Demo)factory.getBean("abstractRef");
    Demo abstractBean1 = (Demo)factory.getBean("abstractRef1");
    System.out.println("Are the 2 instances the same object? " + (abstractBean == abstractBean1));

    The comparison yields that the two instances are distinct.

    Ideally I would expect both references to return the same instance of the Bean.

    Can anyone help me understand what am I missing here?

    Thanks
    Murali

  • #2
    The singleton semantics in Spring is per bean definition, i.e., it only means that whenever you call getBean("abstractRef"), you always get back the same bean. But here you have two distinct bean definitions - abstractRef and abstractRef1. To Spring they are completely different, even thought they are instantiated from the same impl class.

    Comment


    • #3
      If what you state below is true, then this muddies the definition of what a Singleton is. Singletons in java are per Classloader, so you cant have multiple instances of the same class created by a single Classloader.

      I think the attribute name "singleton" is misleading and could confuse folks new to Spring.

      Thanks
      Murali

      Comment


      • #4
        A 'singleton' means there's only one of something. In this case, we're talking about a bean by a certain name (or set of names really, since there can be aliases of course). It's that simple.

        While I get your point, I don't think there's anything implied about the word singleton or the pattern in general that it's connected to a classloader in any fashion, i.e. there's one per classloader. For example, one classic singleton pattern is a static getInstance() method on a class. The only real presumption when using that pattern is that you'll get back the same actual instance each time you call it. Whether there are other instances of the class somewhere in the classloader are irrelevant.

        Regards,

        Comment

        Working...
        X