The Spring framework supports following five scopes,
three of which are available only if we use a web-aware ApplicationContext:
Scope
|
Description
|
Singleton
|
This scopes the bean definition to a single instance
per Spring IOC container (default)
|
Prototype
|
This scopes a single bean definition to have any
number of object instances
|
Request
|
This scopes a bean definition to the HTTP request
|
Session
|
This scopes a bean definition to HTTP session
|
Global-session
|
This scopes a bean definition to a global session.
Suitable for portlet kind of applications
|
The Singleton scope:If
scope is set to Singleton, the Spring IOC container
creates exactly one instance of the object defined by that bean definition.
This single instance is stored in a cache of such singleton beans and all
subsequent requests and references for that named bean returns the cached
object.
The
prototype scope:If
scope is set to
prototype, the Spring IoC container creates new bean instance of the object
every time a request for that specific bean is made.
Bean
class
package
myspring;
public
class HelloWorld {
private
String message;
public void
setMessage(String message){ this.message = message;
}
public void
getMessage(){ System.out.println("Your Message : " + message); }
}
Spring
Scope Test class
package
myspring;
import
org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public
class MainApp {
public
static void main(String[] args) {
ApplicationContext
context = new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld
objA = (HelloWorld) context.getBean("helloWorld");
objA.setMessage("I'm object A"); objA.getMessage();
HelloWorld
objB = (HelloWorld) context.getBean("helloWorld"); objB.getMessage();
} }
Singleton
Scope Beans file
<beans
…..
<bean
id="helloWorld" class=“myspring.HelloWorld" scope="singleton">
</bean>
</beans>
Prototype
Scope Beans file
<beans
…..
<bean
id="helloWorld" class=“mysprin.HelloWorld" scope=“prototype">
</bean>
</beans>
No comments:
Post a Comment