Tech I Enjoy Logo
Custom Search
   Log In    OR    Register  


Home >> Spring Framework >> Spring-Singleton-GOF-Singleton-Difference

Author: Tech I Enjoy !!!

Copyright Notice: All Rights Reserved with Author of this Page.



While studying difference between GOF Singleton pattern and
SpringFramework Singleton scope for the Bean/POJO, I thought of
writing this blog.

As you might be knowing that default scope for the bean within
Spring container is singleton, and while using Spring's ApplicationContext
and BeanFactory we will be getting a single instance to work with..

Thus we may be using the bean instance from the BeanFactory of singleton
in nature, but it is quite different from the GOF Singleton Pattern.

As GOF Singleton Pattern will be looking at an instance that is single or unique per class and per classloader level. But SpringFramework Bean singleton scope is of single in nature but within SpringFramework container boundary/level. So for a particular Spring ApplicationContext and BeanFactory, there could be a single bean instance for a particular bean with a unique id. So let us explore more on this with the help of following example, where I will be creating a single application context and BeanFactory using ClassPathXmlApplicationContext api from SpringFramework by passing this example test.xml configuration file as argument parameter. Then I am retrieving a Bean instance form the BeanFactory using a bean id and then setting value for the instance variable of this Bean instance. On retrieving another Bean instance for the second time for the same bean id as that of bean id used in the first case. Just to imagine in case Spring container manages singleton scope for this Bean, then I should expect the value set in the first case, to be retained in the second case as well.
import org.springframework.beans.factory.*;
import org.springframework.context.*;
import org.springframework.context.support.*;

public class Testclient{
  public Testclient() {
    try{
        ApplicationContext appContext =
            new ClassPathXmlApplicationContext("test.xml");
        BeanFactory factory = appContext;
        //Retrieving bean from the bean factory.
        //Bean id as "one"
        One one1 = (One)factory.getBean("one");
        one1.setName("test name");

        //Bean id as "one"
        One one2 = (One)factory.getBean("one");
        System.out.println("Name from the singleton bean :"+one2.getName());
    } catch(Exception ex) {
        ex.printStackTrace();
    }
  }
  public static void main(String args[]) {
      new Testclient();
  }
}
Above bold red color text shows the steps/code used to retrieve Bean instance from Spring container and then some random name value is set to this instance. While the bold blue colored text above, shows the way another bean instance is retrieved from Spring container using the same bean id. The value from the second bean instance will be able to return the value that is already set in the earlier step. This shows that both these instances are the same, thus can be treated as singleton from Spring's singleton scope. This example is then slightly modified to include another instance of SpringFramework's ApplicationContext and BeanFactory instances again, and then the same ways some random value for name field is set in first case, and then the value is retrieved from the another returned Bean instance from Spring Container. But now there is a difference being observed, the returned value is null, not the original value that is set in first case.
import org.springframework.beans.factory.*;
import org.springframework.context.*;
import org.springframework.context.support.*;

public class Testclient{
  public Testclient() {
    try{
        ApplicationContext appContext =
            new ClassPathXmlApplicationContext("test.xml");
        BeanFactory factory = appContext;
        //Retrieving bean from the bean factory.
        One one1 = (One)factory.getBean("one");
        one1.setName("test name");

        ApplicationContext appContextNew =
            new ClassPathXmlApplicationContext("test.xml");
        BeanFactory factoryNew = appContextNew;
        One one2 = (One)factoryNew.getBean("one");
        System.out.println("Name from the singleton bean :"+one2.getName());
    } catch(Exception ex) {
        ex.printStackTrace();
    }
  }
  public static void main(String args[]) {
      new Testclient();
  }
}
The above modified code uses two different Spring Context and so we have two different bean instances, while one context taking the setter value and the other context returning null value. Code for the Bean in this example, is as follows:
public class One
{
  private String name;
  public void setName(String arg) {
	  name = arg;
  }
  public String getName() {
	  return name;
  }
}
and the Spring configuration file as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
  "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <bean id="one" class="One">
  </bean>
</beans>
Please write your comments about this example, using below form. If anything missed out , please let me know at techienjoy at yahoo . com

Some of the other Articles you may would like to read :
Spring Batch Framework Example :
Spring Batch Framework Example source code
 and Step by step code walkthrough
Spring Framework Remote Session Bean :
Spring Framework Example source code of
Remote Session Bean.
Example using Spring DAO with Hibernate :
Example using Spring DAO with Hibernate Framework.
Spring Framework Web Example :
Spring Framework Web Example source code Explained.
Interview Questions with answer on Spring Framework :
Interview Questions with answer on Spring Framework.
Spring Framework Singleton Example :
Spring Framework Singleton Example source code 
compared with GOF Singleton.
Spring Framework Web Example and WSDL :
Spring Framework Web Example source code
with WSDL.Step by step code walkthrough
Spring Framework Example :
Spring Framework Example source code Explained.
Step by step code walkthrough
Example using Spring with Hibernate :
Example using Spring with Hibernate Framework and use
Current Session Context.
Example using Spring with Hibernate :
Example using Spring with Hibernate Framework Part 1.
Spring Framework Web Example :
Spring Framework Web Example source code Explained.
Example using Spring DAO with Hibernate :
Example using Spring DAO with Hibernate Framework Part 2.
Spring Framework MVC and Tiles :
Spring Framework MVC and Tiles with Example 
source code explained.
Example using Spring with Hibernate :
Example using Spring with Hibernate Framework Part 2.
Spring Framework Local Stateless Session bean :
Spring Framework Local Stateless Session bean with
example source code explained.


References :
Tags: spring dao hibernate example
Tags: spring hibernate dao example
Tags: spring hibernate example 2
Tags: spring hibernate example current session context
Tags: spring hibernate example
Tags: Spring Interview Questions Answer
Tags: Spring Local SLBean
Tags: Spring MVC Tiles2
Tags: Spring Remote SLBean
Tags: Spring Singleton GOF Singleton Difference
Tags: spring web example
Tags: spring ws example
Tags: Spring
Tags: springws example wsdl

Any source code found on any of the page(s) in Techienjoy.com is associated with following notice:
 /*
 * TECHIENJOY.COM MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. TECHIENJOY.COM SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 *
 * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
 * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
 * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
 * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
 * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
 * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
 * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). TECHIENJOY.COM
 * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
 * HIGH RISK ACTIVITIES.
 */


For any of the content, if you would like to bring it to notice for removal from this web site, please write to this web site administrator @ EMAIL-ID,
with appropriate concern and supporting proof(s). After thorough review and if found genuine concern, we would take appropriate action and 
remove disputed content from this web site within 24 hours starting from the time it has brought to our notice.


The content provided in this page is not warranted and/or not guaranteed by techienjoy.com. techienjoy.com is not liable for any negative 
consequences that may result/arise from implementing directly/indirectly any information covered in these pages/articles/tutorials.

All contents of this site is/are written and provided on an "AS IS" basis, without WARRANTIES or conditions of any kind, either express
or implied, including, without limitation, merchantability, or fitness for a particular purpose. You are solely responsible for determining 
the appropriateness of using or refering this and assume any risks associated with this.

This web site is optimized for learning and training. Examples might be simplified to improve reading and basic understanding only. 
This web site content are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. 
In spite of all precautions taken to avoid any typo in these pages, there might be some issues like grammatical mistakes and typos 
being observed in these pages, techienjoy.com extends sincerest apologies to all our visitors for the same.

While using this web site, you agree to have read and accepted our terms of use and privacy policy.


Android Examples || Android Training || Struts 1 || Spring Framework || Software Architecture || Servlet || Log4j Framework || JSP || JSF || JPA || JMS || Hibernate Framework || Enterprise Java || EJB || Design Patterns || Build Tools/Frameworks || Android Platform || ESB || Struts 2 || Core Java

© Copyright 2010-2014, TECHIENJOY.COM, All Rights Reserved.      Privacy Policy     Disclaimer & Terms & Conditions