Why Spring bean is singleton scope?

后端 未结 2 1632
迷失自我
迷失自我 2021-02-06 06:07

I am working with Hibernet and Spring it\'s going good..but I have some doubts

1) why spring scope is singleton by default?Is there any reason for that

2) Can I

相关标签:
2条回答
  • 2021-02-06 06:36

    If you look at Spring closely enough, you'll see that Spring helps you write services, NOT data objects. With Spring, you still have to manage your own domain objects, may it be relational data objects or straight POJOs, and pass them to a Spring managed service, repository, and controller etc as input.

    So, with that in mind, it should be clear why Spring's default scope is NOT prototype, session, or request: we don't need to create a new service every time a request comes in. But why singleton? When a service is stateless, it's thread-safe, and it can scale to any number of concurrent requests, so there's no need for a second copy of the same service.

    Unlike EJB, where there's stateful and stateless beans, Spring has only one type of bean: stateless. If you want to manage state, you'll have to do it yourself. And like previous answer has already pointed out, stateless is by far the better choice because it's faster, more scaleable and easier to maintain, it's also what REST architecture promotes. Stateful beans may appear great on paper, it has been proven over the years as quite a disaster.

    0 讨论(0)
  • 2021-02-06 06:40

    Stateless beans rules :) If you're not going to hold state data in beans then it's enough to have only one instance of each bean. You should also remember that it's not JVM singletons - just Spring singletons. So you don't have to provide only private constructor and any getInstance() methods.

    Quote from Spring documentation:

    When a bean is a singleton, only one shared instance of the bean will be managed and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned.

    Only when you have to keep some session details you should use for example session scope.

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