[英]Using Lombok in immutable Request class
Welcome,欢迎,
I've created simple Rest Controller:我创建了简单的休息控制器:
@RestController
public class MyController {
@PostMapping(value = "/cities", consumes = "application/json", produces = "application/json")
public String getCities(@RequestBody Request request) {
return request.getId();
}
}
I want Request class to be immutable.我希望 Request 类是不可变的。
Is it ok to use Immutable with Lombok this way ?以这种方式将 Immutable 与 Lombok 一起使用可以吗?
import com.google.common.collect.ImmutableList;
import java.beans.ConstructorProperties;
import java.util.List;
import jdk.nashorn.internal.ir.annotations.Immutable;
import lombok.Getter;
import lombok.Value;
@Immutable
@Value
public final class Request {
private final String id;
private final ImmutableList<String> lista;
@ConstructorProperties({"id", "lista"})
public Request(String id, List<String> lista) {
this.id = id;
this.lista = ImmutableList.copyOf(lista);
}
}
Request JSON:请求 JSON:
{
"id":"g",
"lista": ["xxx","yyy"]
}
You can add lombok.config
file to your project with enabled addConstructorProperties
property:您可以使用启用的addConstructorProperties
属性将lombok.config
文件添加到您的项目中:
lombok.anyConstructor.addConstructorProperties=true
then Lombok will generate a @java.beans.ConstructorProperties
annotation when generating constructors.那么 Lombok 在生成构造函数时会生成一个@java.beans.ConstructorProperties
注释。
So you will not need to specify a constructor explicitly:因此,您无需显式指定构造函数:
@Value
public class Request {
private String id;
private ImmutableList<String> list;
}
And Jackson will be able to deserialize your object. Jackson 将能够反序列化您的对象。
More info:更多信息:
Value is immutable itself, no need for @Immutable
.值本身是不可变的,不需要@Immutable
。 To make it Jackson-serializable use Lombok's private @NoArgsConstructor
:要使其 Jackson 可序列化,请使用 Lombok 的私有@NoArgsConstructor
:
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.Value;
@Value
@NoArgsConstructor(force = true, access = AccessLevel.PRIVATE)
public class Request {
Integer id;
String name;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.