简体   繁体   English

Java spring boot,POJO 中的 Lombok 用于响应实体主体

[英]Java spring boot, Lombok in POJO for response entity body

I create an object for default error response body for API.我为 API 的默认错误响应主体创建了一个对象。 So I create my class, i declare constructor and params and I add @Getter and @Setter from lombok.所以我创建了我的类,我声明了构造函数和参数,并从@Setter添加了@Getter@Setter

@Getter
@Setter
public class ResponseError {
    private Date timestamp;
    private int status;
    private int code;
    private String message;
    
    public ResponseError(Date timestamp, int status, int code, String message) {
        this.timestamp = timestamp;
        this.status = status;
        this.code = code;
        this.message = message;
    }   
}

When i initiate the object in body response of ResponseEntity, i got this error on building :当我在 ResponseEntity 的主体响应中启动对象时,我在构建时遇到此错误:

No converter found for return value of type: class com.example.api.controller.response.ResponseError

And if i create manually getter and setter in my class, it is working.如果我在班级中手动创建 getter 和 setter,它就可以工作。 I thought that Lombok do this for me, don't it ?我以为龙目岛为我做这件事,不是吗?

@Getter / @Setter should be applied to a field. @Getter / @Setter应该应用于一个字段。
This should be your code这应该是你的代码

public class ResponseError {

    @Getter
    @Setter
    private Date timestamp;

    @Getter
    @Setter
    private int status;

    @Getter
    @Setter
    private int code;

    @Getter
    @Setter
    private String message;
}

Event better solution for class level, would be to use @Data annotation.类级别的事件更好的解决方案是使用@Data注释。

It generates getters for all fields, a useful .toString method, and .hashCode and .equals implementations that check all non-transient fields.它为所有字段生成 getter,一个有用的.toString方法,以及检查所有非瞬态字段的.hashCode.equals实现。 It will also generate setters for all non-final fields, as well as a constructor.它还将为所有非最终字段以及构造函数生成 setter。 It is equivalent to having all annotations: @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode相当于拥有所有注解: @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode

If you wish to use @Data , your code would be.如果你想使用@Data ,你的代码就是。

@Data
public class ResponseError {
    private Date timestamp;
    private int status;
    private int code;
    private String message;
}
  • Update/install Lombok plugin for Idea更新/安装 Idea 的 Lombok 插件
  • Enable annotation process for Idea为 Idea 启用注释过程在此处输入图片说明
  • Enable annotation process for plugin启用插件的注释过程在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM