Set disallowed fields in Spring Data Rest

感情迁移 提交于 2019-12-13 05:17:45

问题


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.

For example in the class below.

@Entity
public class User {

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

    @CreatedDate
    private LocalDateTime created;

    @LastModifiedDate
    private LocalDateTime lastModified;

    private String name;
}

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");
    }
}

回答1:


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;
}


来源:https://stackoverflow.com/questions/32506315/set-disallowed-fields-in-spring-data-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!