Set disallowed fields in Spring Data Rest

2019-09-10 15:39发布

问题:

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