Set disallowed fields in Spring Data Rest

2019-09-10 16:00发布

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条回答
闹够了就滚
2楼-- · 2019-09-10 16:22

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;
}
查看更多
登录 后发表回答