Why Spring bean is singleton scope?

后端 未结 2 1634
迷失自我
迷失自我 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.

提交回复
热议问题