1

About SpringMVC Controller singleton Then multiple threads request the same method in the same Controller class, whether the thread will be safe? if safe Then when will we use "prototype scope"? Since singleton is so good

ian Huang
  • 23
  • 7

1 Answers1

1

When discussing bean scopes, the Spring docs state:

...use the prototype scope for all stateful beans and the singleton scope for stateless beans.

  1. Prototype scoped controllers have state.

Yes, the controller’s local variables (those declared in methods) are thread-safe, but its instance variables (class-level variables) ARE NOT in singleton-scoped beans. If you want to keep state at the controller level, use prototype scope.

Also, things get complicated when the controller has dependencies to prototype-scoped beans. Once the dependency has been set, it will NOT be reset once a new prototype-scoped bean has been created, defeating the purpose of having that prototype-scoped bean dependency in the first place.

You cannot dependency-inject a prototype-scoped bean into your singleton bean, because that injection occurs only once, when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies. If you need a new instance of a prototype bean at runtime more than once, see Method injection.

You might want to be careful with Method injection, because it’s a fairly advanced feature. So another reason someone might want to use prototype-scoped controllers?

  1. Prototype-scoped controllers allow you to have true prototype-scoped bean dependencies while not having to deal with CGLIB proxying and method injection.

However, consider the performance hit your application might take by using prototype-scoped controllers.

NatFar
  • 2,090
  • 1
  • 12
  • 29