Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin constructor / spring mvc validation

I have this kotlin data class:

data class Message(
    @field:NotEmpty
    val from: String?,
    @field:NotEmpty
    val to: List<String>?,
    @field:NotEmpty
    val subject: String?,
    val cc: List<String>?
)

and when I create a message using my spring mvc api:

@PostMapping("/messages")
@ResponseStatus(HttpStatus.CREATED)
fun create(@Valid message: Message) = service.create(message)

with the following data:

{
   "subject": "this is a test",
   "from": "[email protected]",
   "to": ["[email protected]"],
   "cc": []
}

I got 3 org.springframework.validation.BindException. It seems that the validation occurs between the instantiation of the Message object and the setting of its properties.

Could anyone explain me what is happening and how validation/instantiation occurs in this case ?

like image 710
louis amoros Avatar asked Sep 12 '25 02:09

louis amoros


1 Answers

When u use @Valid then spring boot validate javax && hibernate validation. If you dont want to validate then remove @Valid. Also there missing @RequestBody .

With validation:

@PostMapping("/messages")
@ResponseStatus(HttpStatus.CREATED)
fun create(@Valid @RequestBody message: Message) = service.create(message)

without validation:

@PostMapping("/messages")
@ResponseStatus(HttpStatus.CREATED)
fun create(@RequestBody message: Message) = service.create(message)
like image 150
GolamMazid Sajib Avatar answered Sep 13 '25 18:09

GolamMazid Sajib