Announcement Announcement Module
Collapse
No announcement yet.
Diff between Spring singleton and Singleton design pattern Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Diff between Spring singleton and Singleton design pattern

    I read in the spring docs that spring implementation of singleton is per spring container and the singleton design pattern is per class loader. My questions:-
    1. What if there are multiple class loaders inside the same spring container?
    2. what if there are multiple containers using same class loader.

    I mainly want to know a clear difference between spring implementation of singleton and the singleton design pattern. I have not been able to find a proper answer in any forums.

  • #2
    You already answered yourself..

    I read in the spring docs that spring implementation of singleton is per spring container and the singleton design pattern is per class loader.
    Spring simply creates a new instance of that class and that is available in the container to all class loaders which use that container (provided that they can see the class files needed!).

    For the singleton (anti)pattern the reference to the instance is stored in a static class variable (which is why it is only available per class loader).

    So in situation 1 you get 1 instance situation 2 you get multiple instances (per container remember!).

    Comment


    • #3
      Ok, now I get that, but lets say we do:-
      <bean id = "foo1" class = "Foo" singleton = "true"/>
      <bean id = "foo2" class = "Foo" singleton = "true"/>
      can we not still create 2 instances in the same container?

      Comment


      • #4
        You get 2 instances because that is what you have defined, 2 beans of the same type. I strongly suggest the reference guide which explains the singleton definition in spring...

        Singleton in spring means the bean is created and used amongst all beans that reference that same bean. There is 1 instance of a bean not 1 instance of class (so to speak)...

        Code:
        <bean id="foo1" class=".."/>
        
        <bean id="bar1" class="..>
          <property name="foo" ref="foo1" />
        </bean>
        
        <bean id="bar2" class="..>
          <property name="foo" ref="foo1" />
        </bean>
        Bar1 and bar2 reference the same instance (singleton) of the bean... Now if the scope of been 'foo1' would be, for instance, prototype you would get a new instance of the bean for both 'bar1' and 'bar2'.

        Comment


        • #5
          Spring singleton beans vs Singleton design pattern

          Found a good example here

          Comment

          Working...
          X