首页 > 解决方案 > Spring Boot Rest Api 不显示验证消息

问题描述

我正在使用 Spring Boot 开发一个小型 REST API。我在我的实体类中使用验证注释:

@NotEmpty(message="Please enter a first name")
private String firstName; 

这是我的控制器和服务:

@RestController
public class CustomerController {

    @Autowired
    private CustomerService userService;

    @PostMapping("/customer")
    @ResponseStatus(HttpStatus.CREATED)
    public Customer postUser (@RequestBody @Valid Customer customer){

      return userService.save(customer);

    } 
}
public class CustomerService {

    @Autowired
    private CustomerRepository repository;

    @Transactional
    public Customer save ( Customer customer){

        return repository.save(customer);
    }
}

这是我尝试发送带有空 firstName 值的 JSON 时得到的响应:

{
    "timestamp": "2020-06-08T08:40:08.660+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "",
    "path": "/MVCwebshop/customer"
}

如您所见,我得到的 JSON 中的“消息”字段为空。当我尝试使用默认消息时也会发生这种情况。我怎样才能解决这个问题?

标签: javaspringspring-bootspring-mvc

解决方案


如果使用 Spring Boot 2.3.0.RELEASE 你必须设置

server.error.include-message=always

在您的 application.properties(或 yaml)中。

这里


推荐阅读