Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Spring: Singleton scope

This is the default scope. Spring IOC container creates one instance of the bean, and all requests for beans with an id or ids matching that bean definition result in that one specific bean instance being returned by the Spring container.

Find the following application.
package com.sample.pojo;

public class Author {
private String firstName;
private String lastName;
private String dateOfBirth;
private String country;

public Author(){
System.out.println("Constructor called");

public String getFirstName() {
return firstName;

public void setFirstName(String firstName) {
this.firstName = firstName;

public String getLastName() {
return lastName;

public void setLastName(String lastName) {
this.lastName = lastName;

public String getDateOfBirth() {
return dateOfBirth;

public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;

public String getCountry() {
return country;

public void setCountry(String country) { = country;




id="osho" name="osho" class="com.sample.pojo.Author">
name="firstName" value="Chandra Mohan" />
name="lastName" value="Jain" />
name="dateOfBirth" value="11 December 1931" />
name="country" value="India" />
package com.sample.test;

import org.springframework.context.ApplicationContext;

import com.sample.pojo.Author;

public class HelloWorld {
public static void main(String args[]) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

Author author1 = context.getBean("osho", Author.class);
Author author2 = context.getBean("osho", Author.class);

System.out.println("author1 = " + author1);
System.out.println("author2 = " + author2);
System.out.println("author1 == author2 : " + (author1 == author2));

((ClassPathXmlApplicationContext) context).close();

Constructor called
author1 = [email protected]
author2 = [email protected]
author1 == author2 : true

As you see the output, author1 and author2 are the same references.

Previous                                                 Next                                                 Home

This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Spring: Singleton scope


Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription