Announcement Announcement Module
Collapse
No announcement yet.
what is a singleton bean ? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • what is a singleton bean ?

    here is a tutorial ..

    Beans defined in spring framework are singleton beans. There is an attribute in bean tag named ‘singleton’ if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in spring framework are by default singleton beans.

    by default beans are singleton !!!

    does that mean , I can do context.getBean("bean_id") ONLY once ? if I do the same again , will it give exception ?

  • #2
    Originally posted by andromeda View Post
    by default beans are singleton !!!

    does that mean , I can do context.getBean("bean_id") ONLY once ? if I do the same again , will it give exception ?
    No, it will return the same reference again and again.

    Comment


    • #3
      When a bean is a singleton (which is by default), it simply means that every time you access the bean, you will get a reference to the same object.

      Consider the following:

      Code:
      <bean id="myBean" class="MyClass" />
      Code:
      Object bean1 = context.getBean("myBean");
      Object bean2 = context.getBean("myBean");
      Object bean3 = context.getBean("myBean");
      bean1, bean2, and bean3 are all the same instance of MyClass.

      Comment


      • #4
        >>>>bean1, bean2, and bean3 are all the same instance of MyClass.


        COLOR="Red"] same instance[/COLOR] .....well....ok ..then its fine.


        However, I remember , when we use private constructor to create a bean instance (singleton) we can not call this multiple times .

        Example: database connection instance created in a private constructor

        Comment


        • #5
          context.getBean("myBean") is not calling the constructor of MyClass. Think of the getBean() method as analogous to the get() method on a Map. The instance of MyClass is referenced in the map, and you're just getting that reference whenever you need it.

          Comment


          • #6
            Originally posted by jamestastic View Post
            context.getBean("myBean") is not calling the constructor of MyClass. Think of the getBean() method as analogous to the get() method on a Map. The instance of MyClass is referenced in the map, and you're just getting that reference whenever you need it.
            Excellent. that is very much helpful.

            Comment


            • #7
              singleton is different in terms of &quot;spring&quot; and &quot;singleton pattern&quot;

              Hi All,,,

              Find the below information from spring documentation

              Please be aware that Spring's concept of a singleton bean is quite different from the Singleton pattern as defined in the seminal Gang of Four (GoF) patterns book. The GoF Singleton hard codes the scope of an object such that one and only one instance of a particular class will ever be created per ClassLoader. The scope of the Spring singleton is best described as per container and per bean. This means that if you define one bean for a particular class in a single Spring container, then the Spring container will create one and only one instance of the class defined by that bean definition. The singleton scope is the default scope in Spring.

              I have also observed by sample test application as we know in singleton pattern class got instantiate once only by class loader, while in case of Spring scope "singleton" means that bean will have excactly one instance for the initialized container. When spring container get intialized again one new bean will get created

              Find below code snippets and output so all your doubt will get clear.

              from applicationContext-jdbc2.xml
              Code:
              <bean id="custService" class="com.app.cust.service.CustService">
              	<property name="custDAO" ref="custDAO" />
              </bean>

              Code:
              ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath*:applicationContext-jdbc2.xml");
              				
              CustService cs1 = (CustService)applicationContext.getBean("custService");
              CustService cs2 = (CustService)applicationContext.getBean("custService");
              CustService cs3 = (CustService)applicationContext.getBean("custService");
              		
              System.out.println(">>>### 1 .."+cs1.toString());
              System.out.println(">>>### 2 .."+cs2.toString());
              System.out.println(">>>### 3 .."+cs3.toString());
              	
              ClassPathXmlApplicationContext applicationContext2 = new  ClassPathXmlApplicationContext("classpath*:applicationContext-jdbc2.xml");
              		
              CustService cs4 = (CustService)applicationContext2.getBean("custService");
              CustService cs5 = (CustService)applicationContext2.getBean("custService");
              CustService cs6 = (CustService)applicationContext2.getBean("custService");
              	
              System.out.println(">>>### 4 .."+cs4.toString());
              System.out.println(">>>### 5 .."+cs5.toString());
              System.out.println(">>>### 6 .."+cs6.toString());

              and output logs
              Code:
              Aug 6, 2010 11:04:29 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
              INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@144c984: startup date [Fri Aug 06 11:04:29 UTC 2010]; root of cont
              ext hierarchy
              Aug 6, 2010 11:04:30 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
              INFO: Loading XML bean definitions from URL [file:/D:/MSTR-Customization/apache-tomcat-5.5.28/webapps/CustApp/WEB-INF/classes/applicationContext-jdbc2
              .xml]
              Aug 6, 2010 11:04:30 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
              INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@d15c2c: defining beans [org.springframework
              .aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction
              .interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,custService,custDAO,custDataSource,dsJndiTempl
              ate,txnManager,jdbcTemplate]; root of factory hierarchy
              >>>### 1 ..com.app.cust.service.CustService@1895df8
              >>>### 2 ..com.app.cust.service.CustService@1895df8
              >>>### 3 ..com.app.cust.service.CustService@1895df8
              Aug 6, 2010 11:04:31 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
              INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1788424: startup date [Fri Aug 06 11:04:31 UTC 2010]; root of cont
              ext hierarchy
              Aug 6, 2010 11:04:31 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
              INFO: Loading XML bean definitions from URL [file:/D:/MSTR-Customization/apache-tomcat-5.5.28/webapps/CustApp/WEB-INF/classes/applicationContext-jdbc2
              .xml]
              Aug 6, 2010 11:04:31 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
              INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@ed0f19: defining beans [org.springframework
              .aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction
              .interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,custService,custDAO,custDataSource,dsJndiTempl
              ate,txnManager,jdbcTemplate]; root of factory hierarchy
              >>>### 4 ..com.app.cust.service.CustService@1900174
              >>>### 5 ..com.app.cust.service.CustService@1900174
              >>>### 6 ..com.app.cust.service.CustService@1900174

              Comment


              • #8
                Singleton beans and thread safety in web application

                I have a question: Should we make sure that all methods in a singleton scoped bean are synchronized to make it thread safe in web application? Can anyone explain why or why not? Thanks.

                Comment


                • #9
                  I think spring container can be initialize in web application by 2 ways

                  1. you can initialize the container at each time user get login, by this way you dont need to make methods synchronized as each time user session will get unique copy of spring bean and should be fine.

                  2. you can initialize at server start up, but in this way the same bean can be available to each user session, and in this scenario you need to take extra care while accessing spring bean, and if you declare methods as synchronized then performance will be impacted, lets say user-1 gets login and do some activity and by the same time user-2 also gets login and do similar activity then user-2 will not be able to do anything until user-1 comes out from the same method.

                  So i suggest option 1 is better and I dont think you need to declare methods under bean as synchronized. Yes if you have any such specific scenario in which any specific method is going to call from many places and suppose to run in synchronized manner then only you can go for synchronized for that method...

                  I would like any expert to throw some more light and put your suggestion....

                  -Ronak

                  Comment


                  • #10
                    Hi Ronak:
                    Thanks for your input. About option 1, even if you initialize spring container more then once using the same xml (say application_context.xml) it still is the same container and any singleton scoped beans are shared among all requests. Does that make sense? As developers we should know more about the singleton scope and web applications using spring. I'm still worried about thread safety issue with singletons!

                    Comment


                    • #11
                      Generally these Singleton beans are not STATEFUL (its STATELESS) like Services, Repositories etc. So thread safety among them is not issue

                      Comment


                      • #12
                        Hi Rohan:
                        Can you please pin point where did you find 'Singleton beans are not STATEFUL (its STATELESS)' in spring documentation? This will be very helpful and will make using singleton beans in web apps very easy o use knowing they are already thread safe by design. I'm just worried that spring container will return same object reference again and again whenever we request the beans. Thanks for your response.

                        Comment


                        • #13
                          Guys, Document describe how & where we can use Spring, not other standard coding. Usually Service layer provides data from underline Repository in a way desired for Controller. That is only functionality it provides(I am excluding some important functionality here for better understanding, although its equally important like transaction management). So making this Service singleton it won't affect code though Spring return same instance and this is the beauty. Similarly for Repository(Although its not completely Stateless)

                          Comment

                          Working...
                          X