Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Request and Prototype Scope?

Tags:

Below are the definitions of prototype and request scope in Spring.

prototype Scopes a single bean definition to any number of object instances.

request Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

As per my understanding In case of prototype scope , some pool will be maintained by core container. It will serve the bean instance from that pool. In case of request scope, new bean will be served for each http request. Please correct me if there is some dicrepency in understanding?

If above statements are true, then if bean is holding some state then the scope should not be defined as prototype rather it should be defined as request. Correct?

like image 529
M Sach Avatar asked Jun 25 '11 19:06

M Sach


People also ask

What is difference between prototype and request scope Spring?

Prototype scope creates a new instance every time getBean method is invoked on the ApplicationContext. Whereas for request scope, only one instance is created for an HttpRequest.

What is Spring prototype scope?

The prototype scopeIf the scope is set to prototype, the Spring IoC container creates a new bean instance of the object every time a request for that specific bean is made. As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans.

What is the difference between singleton and prototype scope in Spring?

Singleton: means single bean definition to a single object instance per Spring IOC container. Prototype: means a single bean definition to any number of object instances.

What is request scope in Spring?

A request-scoped bean is an object managed by Spring, for which the framework creates a new instance for every HTTP request. The app can use the instance only for the request that created it. Any new HTTP request (from the same or other clients) creates and uses a different instance of the same class (figure 2).


1 Answers

Prototype creates a brand new instance every time you call getBean on the ApplicationContext. Whereas for Request, only one instance is created for an HttpRequest. So in a single HttpRequest, I can call getBean twice on Application and there will only ever be one bean instantiated, whereas that same bean scoped to Prototype in that same single HttpRequest would get 2 different instances.

HttpRequest scope

Mark mark1 = context.getBean("mark");  Mark mark2 = context.getBean("mark");  mark1 == mark2; //This will return true  

Prototype scope

Mark mark1 = context.getBean("mark");  Mark mark2 = context.getBean("mark");  mark1 == mark2; //This will return false  

Hope that clears it up for you.

like image 170
KARTHIK Avatar answered Sep 21 '22 15:09

KARTHIK