spring @RequestBody class 应该是单例还是原型?

Should spring @RequestBody class be singleton or prototype?

在下面的简单spring rest controller class中,@RequestBody模型object/component AUser应该是单例还是原型。我想检查一下,因为每个请求都由一个单独的线程提供服务,该线程具有不同的 AUser 值,因此如果 AUser class 是默认的 Singleton 类型,那么来自多个线程同时命中并覆盖彼此的数据。

@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;    
}

AUser 或用作 @RequestBody 参数的任何其他类型都不需要成为 bean。

当 Spring MVC 在调用 sayHello 之前处理请求时,将使用请求的主体创建并填充 AUser 的新实例。这是使用 HttpMessageConverter 作为 described in the Spring Framework reference documentation 完成的。 sayHello 然后将使用特定于该方法调用的 AUser 实例进行调用。

documentation1 and documentation2 spring 中所述,使用 HttpMessageConverter 将输入转换为稍后可以在控制器方法中使用的对象。

对于 Json 类型的消息,可以在包 org.springframework.http.converter.json 下找到嵌入在 spring 框架中的 HttpMessageConverter 实现。其中一些转换器使用 Jackson 库,而不是 Gson 库,还有一些是自定义的。

要点是所有这些库(Jackson、Gson)都不会创建 Spring beans。它们只是调用您希望实例化的 class 的构造函数,然后使用 http 消息体填充实例化对象的字段。所以最终他们创建的对象是一个简单的 java 实例。不是由 spring 处理并且属于 spring 上下文的代理实例。

你可以去看看 Jackson 库的 ObjectMapper,看看它是如何工作的。