【问题标题】:Set disallowed fields in Spring Data Rest在 Spring Data Rest 中设置不允许的字段
【发布时间】:2015-12-07 00:03:34
【问题描述】:

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

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

例如在下面的类中。

@Entity
public class User {

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

    @CreatedDate
    private LocalDateTime created;

    @LastModifiedDate
    private LocalDateTime lastModified;

    private String name;
}

我尝试使用 @ReadOnlyProperty 注释,但没有版本字段的设置器。但是没有任何效果,用户仍然可以自己设置版本字段。我还尝试实现如下所示的全局初始化程序,但没有成功。活页夹被捡起来了。

@ControllerAdvice
public class GlobalInitializer {

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

【问题讨论】:

  • 谢谢,但这不是我要问的。我不想公开某些方法,如 PUT 或 DELETE,但不允许设置某些公开字段
  • 也许是 Jackson JSONView?
  • 这似乎是个好主意,但我认为不能用“JsonView”注释一个用“RepositoryRestResource”注释的存储库。所以我必须为每个存储库编写一个控制器,但是我可以自己手动删除该字段...

标签: java spring spring-mvc spring-boot spring-data-rest


【解决方案1】:

您应该将@JsonIgnore 放在字段和setter 上,并将@JsonProperty("propertyName") 放在getter 上。

刚刚测试过 - 对我有用:

@JsonIgnore
@LastModifiedDate
private LocalDate lastUpdated;

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

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

【讨论】:

  • 我已将此答案标记为正确。唯一需要的是 setter 字段上的 @JsonIgnore,其他注释取决于您的要求。谢谢!
猜你喜欢
  • 2013-08-21
  • 2014-11-02
  • 1970-01-01
  • 2017-08-26
  • 1970-01-01
  • 2021-01-27
  • 1970-01-01
  • 2017-03-14
  • 1970-01-01
相关资源
最近更新 更多