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]

Comment: Jay at Do, 21 Okt 11:19 PM

Hi,

Do you have a simple example of Spring working? I can't seem to get it to cache values locally using a basic desktop application. Do you have a VERY simple example of a desktop app using spring? one/two method app would be great!!

Cheers,
Jay

Comment: Asha at Mi, 12 Jan 12:42 PM

Can you please specify few companies that makes software product using Spring framework

Your comment:

(not displayed)
 
 
 

Live Comment Preview: