Is there a new bean object created with every request in spring mvc?

前端 未结 1 1135
悲哀的现实
悲哀的现实 2020-12-18 13:43

I am not able to understant that only one bean object is created in spring mvc using dispatcher servlet or a new object gets created with every request?

Controller c

相关标签:
1条回答
  • 2020-12-18 14:24

    Spring's application context (the bean IoC container, which is responsible for managing bean lifecycle from its instantiation to its destruction) contains bean definitions. These definitions among other attributes contain so called scope. This scope can have the following values:

    • singleton - only one instance of the bean is created during the application lifetime
    • prototype - every time someone asks (applicationContext.getBean(...)) for this bean a new instance is created

    You can have some special scopes as well:

    • request - bean lifecycle is bound to the HTTP request
    • session - bean lifecycle is bound to the HTTP session

    You can even create your own scopes. The default scope for beans is singleton. So if you don't specify otherwise, the bean is singleton (single instance per application).


    If you are using component-scan which searches for classes annotated with @Component-like annotations (e.g. @Controller), then these classes are automatically registered as bean definitions in application context. The default scope applies to them as well.

    If you want to alter scope of these auto-registered beans, you have to use @Scope annotation. Check its JavaDoc if you are interested in how to use it.


    TL;DR Your LoginController is singleton.

    0 讨论(0)
提交回复
热议问题