Sunday 16 April 2017

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.

Author.java
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) {
  this.country = country;
 }

}

myConfiguration.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

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

</beans>

HelloWorld.java
package com.sample.test;

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

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();
 }
}

Output
Constructor called
author1 = com.sample.pojo.Author@63753b6d
author2 = com.sample.pojo.Author@63753b6d
author1 == author2 : true

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



Previous                                                 Next                                                 Home

No comments:

Post a Comment