在 Spring Data Rest 中设置不允许的字段 [英] Set disallowed fields in Spring Data Rest

查看:23
本文介绍了在 Spring Data Rest 中设置不允许的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 POST 到我的存储库中排除某些字段.

I want to exclude certain fields from a POST to my repositories.

例如我想自己设置版本,这样用户就不能自己设置这个字段.

For example I want to set the version myself so users cannot set this field themselves.

例如在下面的课程中.

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @CreatedDate
    private LocalDateTime created;

    @LastModifiedDate
    private LocalDateTime lastModified;

    private String name;
}

我尝试使用 @ReadOnlyProperty 注释并且没有版本字段的设置器.但是没有任何效果,用户仍然可以自己设置版本字段.我也尝试过实现一个像下面这样的全局初始化器,但没有成功.活页夹被捡起来了.

I have tried to use the @ReadOnlyProperty annotation and not having a setter for the version field. But nothing worked, users can still set the version fields themselves. I have also tried to implement a global initializer like below, but without success. The binder gets picked up though.

@ControllerAdvice
public class GlobalInitializer {

    @InitBinder
    public void globalBinder(WebDataBinder webDataBinder) {
        webDataBinder.setDisallowedFields("name");
    }
}

推荐答案

你应该把 @JsonIgnore 放在 field 和 setter 上,把 @JsonProperty("propertyName") 放在 getter 上.

You should place @JsonIgnore on field and on setter, and place @JsonProperty("propertyName") on getter.

刚刚测试过 - 对我有用:

Just tested - works for me:

@JsonIgnore
@LastModifiedDate
private LocalDate lastUpdated;

@JsonProperty("lastUpdated")
public LocalDate getLastUpdated() {
    return lastUpdated;
}

@JsonIgnore
public void setLastUpdated(LocalDate lastUpdated) {
    this.lastUpdated = lastUpdated;
}

这篇关于在 Spring Data Rest 中设置不允许的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆