Spring Request and Prototype Scope?

后端 未结 3 1345
忘了有多久
忘了有多久 2020-12-13 00:53

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

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

request Sc

相关标签:
3条回答
  • 2020-12-13 01:28

    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.

    0 讨论(0)
  • 2020-12-13 01:38

    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.

    0 讨论(0)
  • 2020-12-13 01:47

    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 讨论(0)
提交回复
热议问题