我试图将请求正文解析为 Ship 对象
@PostMapping("/ships")
public Ship createShip(@RequestBody Ship ship){
return ship;
}
而当 Ship 对象被反序列化时,spring 只对字段使用注入值。但我希望这个领域的春天使用设置器。
我尝试将注释 @JsonSetter 添加到 setter 并且效果很好。但我认为这是不好的方式。
@Entity
public class Ship {
@Id
@GeneratedValue
private Long id;
private String name;
private String planet;
public String getName() {
return name;
}
@JsonSetter
public void setName(String name) {
if(name == null || name == "") throw new IllegalArgumentException("Error while setting name. Can't be null and empty");
if(name.length() > 50) throw new IllegalArgumentException("Error while setting name. Can't be mere than 50 chars");
this.name = name;
}
public String getPlanet() {
return planet;
}
@JsonSetter
public void setPlanet(String planet) {
if(planet == null || planet == "") throw new IllegalArgumentException("Error while setting planet. Can't be null and empty");
if(planet.length() > 50) throw new IllegalArgumentException("Error while setting planet. Can't be mere than 50 chars");
this.planet = planet;
}
}
可能存在一些这样的注释:
createShip(@RequestBody(access = METHODS) Ship ship)
或者
@Entity
@JsonDeserialize(access=METHODS)
public class Ship {