tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Spring > Core > Singleton Scope

Singleton Scope 

Spring Inversion of Control (IoC) also known as Dependency Injection (DI) is a process by which objects define their dependencies with collaborating objects. Singleton scoped bean permits a single bean definition to a single object instance per Spring IoC container. It is the default scope of Spring IoC container.

File Name  :  
/SpringCore001/conf/scope/singleton.xml 

File Name  :  
com/bethecoder/tutorials/spring3/basic/SimpleBean.java 
   
package com.bethecoder.tutorials.spring3.basic;

public class SimpleBean {

  private String simpleProp;

  public String getSimpleProp() {
    return simpleProp;
  }

  public void setSimpleProp(String simpleProp) {
    this.simpleProp = simpleProp;
  }
  
}
   

File Name  :  
com/bethecoder/tutorials/spring3/tests/scope/SingletonTests.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.spring3.tests.scope;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bethecoder.tutorials.spring3.basic.SimpleBean;

public class SingletonTests {

  /**
   @param args
   */
  public static void main(String[] args) {
    
    System.out.println("Initializing ApplicationContext");
    ApplicationContext factory = new ClassPathXmlApplicationContext("singleton.xml");
    System.out.println("ApplicationContext Initialized");
    
    System.out.println("Accessing first bean");
    SimpleBean first = (SimpleBeanfactory.getBean("first");
    System.out.println(first);

    first = (SimpleBeanfactory.getBean("first");
    System.out.println(first);

    System.out.println("Accessing second bean");
    SimpleBean second = (SimpleBeanfactory.getBean("second");
    System.out.println(second);

    second = (SimpleBeanfactory.getBean("second");
    System.out.println(second);
  }

}
   

It gives the following output,
Initializing ApplicationContext
ApplicationContext Initialized

Accessing first bean
com.bethecoder.tutorials.spring3.basic.SimpleBean@1ce3fc5
com.bethecoder.tutorials.spring3.basic.SimpleBean@1ce3fc5

Accessing second bean
com.bethecoder.tutorials.spring3.basic.SimpleBean@1bcdbf6
com.bethecoder.tutorials.spring3.basic.SimpleBean@1bcdbf6



 
  


  
bl  br