Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring RequestScope

Please see the example below. I wonder if there will be any difference if I specify the scope or not below. 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();
  }
}

like image 473
Lisa Avatar asked Aug 26 '26 17:08

Lisa


1 Answers

By default, all Spring managed beans have 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.

However, in the first implementation, since you are annotating UserResource with @RequestScope, Spring will create a new controller object to serve each request. This means that any state information you may be maintaining in UserResource will be lost. All member variables of UserResource will also be created anew for each request.

Although I am curious as to why you would want a controller to be request scoped? Could you please share your use-case, if possible?

Here is a good article to read on the subject: Spring Bean Scopes

like image 70
Meet K. Avatar answered Aug 29 '26 07:08

Meet K.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!