January 04, 2010

Spring scope

« Rsync Examples | Main | ApplicationContextAware - access application context from bean »

The default scope of a spring bean is singleton. In distributed systems it can be dangerous if more than one thread access to singleton scoped bean objects, which perhaps are not thread safe. That's why the Springframework defines more scopes and enables to define new own scopes.

Springframework scopes:

  • singleton - only one instance for all references or "getBean"-method calls
  • prototype - creates new object instances of the bean by reference or on "getBean"-method calls
  • request - create new objects of bean class for every new HTTP request
  • session - create new objects of bean class for every new session

Application context configuration:
<bean id="singletonBean" class="java.lang.Object"/>
<bean id="prototypeBean" class="java.lang.Object" scope="prototype"/>
Java Code:
ApplicationContext appContext = new ClassPathXmlApplicationContext("scope-ctx.xml");

Object prototypeBean1 = appContext.getBean("prototypeBean");
Object prototypeBean2 = appContext.getBean("prototypeBean");
System.out.println(prototypeBean1.equals(prototypeBean2)); //-> false

Object singletonBean1 = appContext.getBean("singletonBean");
Object singletonBean2 = appContext.getBean("singletonBean");
System.out.println(singletonBean1.equals(singletonBean2)); //-> true

Regards,
Rafael Sobek

Technorati Tags:

Posted by rafael.sobek at 4:48 PM in Spring

 

[Trackback URL for this entry]

Your comment:

(not displayed)
 
 
 

Live Comment Preview:

 
« January »
SunMonTueWedThuFriSat
     12
3456789
10111213141516
17181920212223
24252627282930
31