20
votes

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?

3
Best explanation. One more question : For prototype-scope bean "The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding." What is about request scope bean. Does request scoped bean will take care by IOC container? Thanks :) - Md. Sajedul Karim

3 Answers

19
votes

You are off. Prototype is described in the docs here as

"The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made."

Your description of request scoped beans is accurate.

Probably just got the wires crossed vis-a-vis prototype vs singleton.

143
votes

Best one i found on net

Prototype creates a brand new instance everytime 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.

0
votes

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.

So in an HttpRequest, if the getBean method is called twice on Application and there will be only one bean instantiated and reused, whereas the bean scoped to Prototype in that same single HttpRequest would get 2 different instances.