joven
joven

Reputation: 391

Should spring @RequestBody class be singleton or prototype?

In the simple spring rest controller class below, should the @RequestBody model object/component AUser be singleton or prototype. I want to check this because, each request is served by a separate thread with different values for AUser, so if the AUser class is of default Singleton type, won't the requests from various threads hitting simultaneously override each others data.

@RestController
@Component
public class ExampleController {           
    @PostMapping("/hello")
    public String sayHello(@RequestBody AUser user) {
        return "hello " + user.userName + " from " + user.userCity;
    }
}   

@Component
class AUser {
   public String userName;
   public String userCity;    
}

Upvotes: 0

Views: 904

Answers (2)

Andy Wilkinson
Andy Wilkinson

Reputation: 116171

There’s no need for AUser, or any other type that is used as a @RequestBody parameter, to be a bean.

When Spring MVC is handling the request prior to calling sayHello, a new instance of AUser will be created and populated using the request’s body. This is done using an HttpMessageConverter, as described in the Spring Framework reference documentation. sayHello will then be called with an AUser instance that is specific to that invocation of the method.

Upvotes: 1

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 19108

As described in the documentation1 and documentation2 spring uses HttpMessageConverter to convert the input into an Object which later you can use in the controller method.

For Json type of messages the HttpMessageConverter implementations that are embedded in spring framework can be found under the package org.springframework.http.converter.json. Some of those converters use the Jackson library other the Gson library and some some more custom.

Point is that all those libraries (Jackson, Gson) don't create Spring beans. They just call the constructor of the class that you expect to be instantiated and then use the http message body to fill the fields of the object that was instantiated. So in the end the object that they create is a simple java instance. Not a proxy instance which is handled by spring and belongs to the spring context.

You can go and check for example ObjectMapper of Jackson library and see how it works.

Upvotes: 3

Related Questions