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();
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With