Spring 具有生成默认值的请求主体的休息控制器?

Spring rest controller having a request body with generated default value?

我可以在我的休息控制器上请求负载,例如

{
"id" : "dffds-fsdf-dfdf-dsf",
"name" : "toto",
"age" : "18"
}

但是body参数id不是必须的,可以为空。在这种情况下,我需要生成一个 ID(使用 UUID 或其他任何东西)

有没有办法使用注释来做到这一点?

您可以这样做的一种方法是将默认值分配给变量,因此如果 body 参数 id 为空,则将分配此默认值,但如果在 body 中传递 id,则不会分配此默认值。

public class Model {

private String name;

private String id=UUID.randomUUID().toString();

private int age;

}

我们至少要解决两种情况:

  1. id 字段 发送为 null,例如{ "id": null, ... }
  2. id 字段在有效载荷中 不存在 ,例如{ "name" : "toto", "age" : "18" }

似乎没有可以产生此行为的注释,但以下有效负载映射 class 应该可以解决问题:

import java.util.UUID;

public class Payload {

    private String id = UUID.randomUUID().toString();
    private String name;
    private String age;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id != null ? id : UUID.randomUUID().toString();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    /* You can safely remove this method, it's here only for test purposes. */
    public static void main(String... args) throws java.io.IOException {
        String[] tests = new String[] { 
                "{ \"id\": \"dffds-fsdf-dfdf-dsf\", \"name\": \"toto\", \"age\": \"18\" }", 
                "{ \"name\": \"toto\", \"age\": \"18\" }", 
                "{ \"age\": \"18\" }", 
                "{ \"id\": null, \"name\": \"toto\", \"age\": \"18\" }",
                "{ \"id\": null, \"age\": \"18\" }", 
                "{ \"id\": null, \"name\": \"toto\" }", 
                "{ \"id\": null }", 
                "{ }" 
            };

        for (String it : tests) {
            Payload payload = new com.fasterxml.jackson.databind.ObjectMapper().readValue(it, Payload.class);
            System.out.println(it + " => [id=" + payload.getId() + ", name=" + payload.getName() + ", age=" + payload.getAge() + "]");
        }
    }
}

如果您 运行 main 方法,您将获得如下输出,应该符合您的要求:

{ "id": "dffds-fsdf-dfdf-dsf", "name": "toto", "age": "18" } => [id=dffds-fsdf-dfdf-dsf, name=toto, age=18]
{ "name": "toto", "age": "18" } => [id=f3218a7c-6e2c-47fc-93b9-746ceec7b56b, name=toto, age=18]
{ "age": "18" } => [id=21899f52-d273-4c89-8a16-26871f4ec351, name=null, age=18]
{ "id": null, "name": "toto", "age": "18" } => [id=0a2ba8f6-cee3-44f0-89a6-e18ac55346d2, name=toto, age=18]
{ "id": null, "age": "18" } => [id=4f8125eb-ec68-4343-a04f-1490ffb81a76, name=null, age=18]
{ "id": null, "name": "toto" } => [id=b5d59feb-5730-4929-bc41-b0f17da68a39, name=toto, age=null]
{ "id": null } => [id=ccb9b192-daa3-4877-b232-56ec483b9d8e, name=null, age=null]
{ } => [id=d56cc66c-f9af-4dea-8ad4-86c16c9921a7, name=null, age=null]