@RestController
@RequestMapping("/messages")
public class MessageController {
private final Validator validator;
@Autowired
public MessageController(Validator validator) {
this.validator = validator;
}
@PostMapping
public Map<String, Object> send(Message message) {
// 만약에 위의 @Constraints에 위배되는 값이 있다면 이 Set에 들어가게 된다
Set<ConstraintViolation<Message>> violationSet = validator.validate(message);
if (violationSet.isEmpty() == false) {
// 만약에 Message.sender가 null이라면 이 Exception의 메세지는
// [class: Message, property: sender, message: may not be null]
throw new IllegalArgumentException(
violationSet.stream()
.map(violation -> String.format("[class: %s, property: %s, message: %s]",
violation.getRootBeanClass().getSimpleName(),
violation.getPropertyPath().toString(),
violation.getMessage()))
.collect(Collectors.joining(", "))
);
}
// 이하 생략
}
}