我尝试将请求正文解析为 Ship 对象
@PostMapping("/ships")
public Ship createShip(@RequestBody Ship ship){
return ship;
}
当 Ship 对象被反序列化时,spring 仅使用字段的注入(inject)值。但我希望 spring 对这个字段使用 setter。
我尝试向 setter 添加注释@JsonSetter,效果很好。但我认为这很糟糕。
@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 {
最佳答案
将您的 Ship 类保留为 POJO 并验证 setter 中的条件可以组织为 spring manual 中提到的 Spring 验证功能。
使用 spring 验证 bean -
- 定义自定义 validator
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
@Component
public class ShipValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Ship.class.equals(clazz);
}
@Override
public void validate(Object obj, Errors errors) {
Ship ship = (Ship) obj;
String name = ship.getName();
String planet = ship.getPlanet();
if(StringUtils.isEmpty(name)) errors.rejectValue("name", "Can't be null or Empty");
if(StringUtils.isEmpty(planet)) errors.rejectValue("planet", "Can't be null or Empty");
if(name.length() > 50) errors.rejectValue( "name", "Can't be more than 50 chars");
if(planet.length() > 50) errors.rejectValue("planet", "Can't be more than 50 chars");
}
}
- 更改 Controller 以使用此 validator
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ShipController {
@Autowired ShipRepo shipRepo;
@Autowired ShipValidator shipValidator;
@PostMapping("/ships")
public Ship saveShip(@RequestBody Ship ship, BindingResult result) {
shipValidator.validate(ship, result);
if(result.hasErrors()) {
//TODO: add your exception handling logic and handle these errors
throw new IllegalArgumentException("Error in properties");
}
return shipRepo.save(ship);
}
}
关于java - 通过@PostMapping解析对象,使用方法访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61181658/