gpt4 book ai didi

java - Spring Boot 单页应用并发

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:32:51 25 4
gpt4 key购买 nike

我复制了一个示例 Spring Boot SPA。我想了解,如果多人通过 URL 使用该网页会发生什么情况。 Java 是否会在每次调用时创建一个 Web 应用程序实例?内存资源不是共享的,对吧,也就是说,如果附加了一个列表对象,每个用户都会看到自己的列表?

最佳答案

spring-boot bean 的默认范围是单例。假设您的 bean 没有管理状态,您应该可以使用默认行为:

https://docs.spring.io/spring/docs/3.0.0.M3/reference/html/ch04s04.html

4.4.1 The singleton scope

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 by the Spring container.

To put it another way, when you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.

现在,如果您正在使用一个有状态的 bean,并且希望每个请求都使用一个新的 bean,您可以将该 bean 的范围定义为 prototype:

4.4.2 The prototype scope

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 (that is, it is injected into another bean or it is requested via a programmatic getBean() method call on the container). As a rule of thumb, you should use the prototype scope for all beans that are stateful, while the singleton scope should be used for stateless beans.

关于java - Spring Boot 单页应用并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50415529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com