简体   繁体   English

Spring 请求范围

[英]Spring RequestScope

Please see the example below.请看下面的例子。 I wonder if there will be any difference if I specify the scope or not below.我想知道如果我指定 scope 或不在下面是否会有任何区别。 Thanks谢谢

@RestController
@RequestScope
@RequestMapping("/api/v1/user")
public class UserResource {

  @GetMapping("/addresscheck")
  public String getAddress() {
    return customer.getAddress();
  }
}


// Here does it matter I define the scope or not? is it still going to be treated as one per request?
@RestController  
@RequestMapping("/api/v1/user")
public class UserResource {

  @GetMapping("/addresscheck")
  public String getAddress() {
    return customer.getAddress();
  }
}

By default, all Spring managed beans have singleton scope.默认情况下,所有 Spring 托管 bean 都具有singleton scope。 So in your second implementation, only one UserResource object will be created by Spring and that will be provided every time a request for the specified URL is to be fulfilled.因此,在您的第二个实现中,只有一个UserResource object 将由 Spring 创建,并且将在每次满足对指定 URL 的请求时提供。

However, in the first implementation, since you are annotating UserResource with @RequestScope , Spring will create a new controller object to serve each request.但是,在第一个实现中,由于您使用@RequestScope注释UserResource ,因此 Spring 将创建一个新的 controller object 来服务每个请求。 This means that any state information you may be maintaining in UserResource will be lost.这意味着您可能在UserResource中维护的任何 state 信息都将丢失。 All member variables of UserResource will also be created anew for each request. UserResource的所有成员变量也将为每个请求重新创建。

Although I am curious as to why you would want a controller to be request scoped?虽然我很好奇你为什么想要一个 controller 被请求范围? Could you please share your use-case, if possible?如果可能的话,您能否分享您的用例?

Here is a good article to read on the subject: Spring Bean Scopes这是一篇关于该主题的好文章: Spring Bean Scopes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM