“PROTOTYPE”和”REQUEST”作用域的ProxyMode之间的区别

huangapple go评论75阅读模式
英文:

Difference between ProxyMode of PROTOTYPE and REQUEST scope

问题

我创建了一个简单的 Spring Boot 项目。在项目中,我创建了2个接口,分别由2个服务类实现。其中一个服务类带有原型(Prototype)范围的注解,而另一个带有请求(Request)范围的注解。
这两个服务类都使用了代理模式 ScopedProxyMode.INTERFACES

在我的控制器(Controller)类中,我将这两个服务类都自动装配(autowire),然后简单地将对象打印出来。每次我发起HTTP请求时,两者都会给我不同的引用。如果我们可以通过使用 PROTOTYPE 范围来实现相同的效果,那么为什么我们还需要将作用域设置为 REQUEST 呢?

英文:

I created a simple Spring Boot project. In the project, I created 2 interfaces which are implemented by 2 service class. One service class is annotated with Prototype scope while another is annotated with Request scope.
Both the service class have proxy mode ScopedProxyMode.INTERFACES

In my Controller class, I am autowiring both the Service class and simply printing out the object. Both are giving me different references every time I make an HTTP request. Why do we need to set the scope as REQUEST if we can achieve the same thing using PROTOTYPE scope?

答案1

得分: 1

定义
如果一个bean具有PROTOTYPE范围,Spring IoC容器会在每次请求该bean时创建一个新的bean实例。如果一个bean具有REQUEST范围,每个HTTP请求将拥有它自己的bean实例。

示例
在您的示例中,如果您希望在整个HTTP请求的生命周期内使用相同的引用,您应该使用REQUEST范围。

我在这里找到了一个很好的示例,说明了REQUEST和PROTOTYPE范围的bean之间的区别链接

文档

英文:

Definitions
If a bean has PROTOTYPE scope, the Spring IoC container creates a new bean instance every time a request for that bean is made. If a bean has REQUEST scope, every HTTP request will have it's own instance of the bean.

Example
In your example, if you wanted the same reference across the entire lifecycle of your HTTP request, you would want to use REQUEST scope.

I found a nice illustration of the differences between REQUEST and PROTOTYPE scoped beans here.

Documentation

huangapple
  • 本文由 发表于 2020年9月5日 09:37:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/63749714.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定