Sunday, March 25, 2012

Spring bean scope annotation example

Spring bean instance will be created depend on scope specified on that bean , spring container support five types of scope
  • singleton – Return a single bean instance per Spring IoC container
  • prototype – Return a new bean instance each time when requested
  • request – Return a single bean instance per HTTP request.
  • session – Return a single bean instance per HTTP session.
  • globalSession – Return a single bean instance per global HTTP session.
Spring container default scope is singleton , so you have to be careful before use bean instance . In multi-thread environment , singleton instance must be thread safe to avoid race condition . In that situation you might use prototype scope. Other three scopes are only valid in the context of a web-aware Spring ApplicationContext.
Example
Here is an example to explain difference between singleton and prototype .
1. Singleton Example: Since no bean scope is specified ,default to singleton
package com.example.springscope;

import org.springframework.stereotype.Service;

@Service("userService")
// default scope is Singleton
public class User {
 private Integer id;
 private String userName;

 public int getId() {
  return id;
 }

 public void setId(Integer id) {
  this.id = id;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }
   public String toString(){
    return "[ ID : "+id+" Name :"+userName+"]";
   }
}


Configuration XML : component-scan will allow us to use annotation base bean declaration and enable auto component scan. All beans declared in com.example and its child package will be available in spring context.


 
 


Test example :
package com.example.springscope;

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

public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {

  ApplicationContext context = new ClassPathXmlApplicationContext(
    new String[] { "app-config.xml" });
  // retrieve configured instance
  User customerA = (User) context.getBean("userService");
  customerA.setId(1);
  customerA.setUserName("Jeff");
  System.out.println(" Customer Info A:" +customerA);
   // Since Scope is singleton , same instance will be return to caller
  User customerB = (User) context.getBean("userService"); 
  System.out.println(" Customer Info B:" +customerB);
 }

}


Output :
 Customer Info A:[ ID : 1 Name :Jeff]
 Customer Info B:[ ID : 1 Name :Jeff]


In this example Id and name has been set on the customerA but same value is also showing on customerB , because of singleton scope. Spring container will create only one object for singleton scope , that will be return to caller every time.
Prototype Example
If you want new instance every time , you have to use prototype scope .
 package com.example.springscope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service("userService")
@Scope("prototype")
public class User {
 private Integer id;
 private String userName;

 public int getId() {
  return id;
 }

 public void setId(Integer id) {
  this.id = id;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }
   public String toString(){
    return "[ ID : "+id+" Name :"+userName+"]";
   }
}

Test Example :
package com.example.springscope;

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

public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {

  ApplicationContext context = new ClassPathXmlApplicationContext(
    new String[] { "app-config.xml" });
  // retrieve configured instance
  User customerA = (User) context.getBean("userService");
  customerA.setId(1);
  customerA.setUserName("Jeff");
  System.out.println(" Customer Info A:" +customerA);
   // Since Scope is prototype , new instance will be return to caller
  User customerB = (User) context.getBean("userService"); 
  System.out.println(" Customer Info B:" +customerB);   // all fields value will be null
  
  customerB.setId(2);
  customerB.setUserName("Jhon");
  System.out.println(" Customer Info B:" +customerB);  
  
 }

}


Output :
  Customer Info A:[ ID : 1 Name :Jeff]
 Customer Info B:[ ID : null Name :null]
 Customer Info B:[ ID : 2 Name :Jhon]


You can download this example project from github https://github.com/sujanctg2005/Example

Do you like this post? Please link back to this article by copying one of the codes below.

URL: HTML link code: BB (forum) link code:

No comments:

Post a Comment