有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java将(JEP359)记录为Spring控制器请求和响应DTO

我只是在试验这些新的Java记录,我想知道是否可以将它们用作spring boot应用程序中请求/响应类型的DTO

因此,我只是修改了一些代码(类中有很多样板文件getter/setter到记录),编译并启动了我的应用程序。尝试一些rest端点,我得到的只是一个异常,告诉我:

No serializer found for class x.y.CreateNewShopListeCommand$Item and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS

好吧,记录不会创建带有“get”前缀的getter方法。现在我想知道:是否可以使用记录作为spring boot controller的请求/响应类型

编辑:示例应用程序(https://github.com/kaipaysen/playground-jdk14-records-as-dto

// HelloController.java
@RestController
@RequestMapping("/hello")
public class HelloController {
    
    public record HelloRequest(
        @JsonProperty("name") String name
    ) {}

    public record HelloResponse(
        @JsonProperty("message") String message
    ) {}

    @RequestMapping(method = RequestMethod.POST)
    public HelloResponse hello(@RequestBody @Valid HelloRequest query) {
        return new HelloResponse("Hello " + query.name());
    }
    
}

调用curl -X POST -H "Content-Type: application/json" -d '{"name":"Max"}' http://localhost:8080/hello返回{"message":"Hello null"}。调试hello表明请求未正确反序列化。有什么想法吗

编辑#2: 刚刚在FasterXML repo中发现了这个问题。他们正在为杰克逊2.12做这件事


共 (1) 个答案

  1. # 1 楼答案

    您需要将这个类级别的注释添加到您的记录中

    @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)

    在jackson版本1.12中,它应该没有注释

    我认为这是Jackson中的一个错误,你需要在你的记录中添加第二个字段,因为它不适用于只有一个字段的记录