默认情况下,不要使用Spring Data Rest和Jpa公开Entity类中的字段

问题描述 投票:2回答:1

我有一个实体类帐户。它有很多字段。其中大部分现在暴露在REST调用中,除非我明确忽略@JsonIgnore的密码字段,但我将添加更多字段,我不想忘记将@JsonIgnore添加到不应公开的新内容中。

我可以反转曝光,因此我明确必须启用要导出的字段,默认情况下它不会被曝光吗?

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import lombok.Data;
import lombok.ToString;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.fasterxml.jackson.annotation.JsonIgnore;

@Data
@ToString(exclude = "password")
@Entity
public class Account {

    public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder();

    private @Id @GeneratedValue Long id;

    private String name;

    @JsonIgnore private String password;

    private String[] roles;

    public void setPassword(String password) {
        this.password = PASSWORD_ENCODER.encode(password);
    }

    protected Account() {}

    public Account(String name, String password, String... roles) {

        this.name = name;
        this.setPassword(password);
        this.roles = roles;
    }

}

在这里使用Spring Data REST,所以其他所有东西都只是存储库,没有额外的层来做一些聪明的事情。

java spring jackson spring-data-rest
1个回答
2
投票

Jackson库中有两种主要方法可以获得“白名单”属性效果

第一种方式:

@Data类中删除Account注释,并仅将getters添加到要公开的字段。为了确保没有getter的属性不会被排除在你的@JsonIgnoreProperties(ignoreUnknown=true)类中添加Account

第二种方式:

Account课程包装你的AccountForJson课程。例如 :

public class AccountForJson {

private Account account;

public MyClassForJson(Account accountToWrapped) {
    this.account = accountToWrapped;
}

/**
 * Example of property that you want to expose
 */
public String getName() {
    return this.account.getName();
 }
}

p.s:qazxsw poi github存储库中存在一个未解决该功能的问题,这里是观看该问题的链接 - Jackson

© www.soinside.com 2019 - 2024. All rights reserved.