Kotlin and @Valid Spring annotation

I have an entity:

class SomeInfo( @NotNull @Pattern(regexp = Constraints.EMAIL_REGEX) var value: String) { var id: Long? = null } 

And the controller method:

 @RequestMapping(value = "/some-info", method = RequestMethod.POST) public Id create(@Valid @RequestBody SomeInfo someInfo) { ... } 

@Valid annotation does not work.

It seems that Spring needs a constructor without default parameters, and the fancy code above becomes something ugly (but works) as follows:

 class SomeInfo() { constructor(value: String) { this.value = value } @NotNull @Pattern(regexp = Constraints.EMAIL_REGEX) lateinit var value: String var id: Long? = null } 

Any good practice to make it less verbose?

Thanks.

+6
source share
2 answers

Spring seems to require these annotations to be applied to the field. But Kotlin will apply these annotations to the constructor parameter. Use the field: qualifier when applying the annotation to apply it to the field. The following code should work fine for you.

 class SomeInfo( @field:NotNull @field:Pattern(regexp = Constraints.EMAIL_REGEX) var value: String ) { var id: Long? = null } 
+17
source

As an alternative to Michal's answer, getter annotation also works.

 class SomeInfo( @get:NotNull @get:Pattern(regexp = Constraints.EMAIL_REGEX) var value: String ) { var id: Long? = null } 

The annoying part is that not using @get: or @field: annotates the constructor parameter. This is still valid kotlin code (so you won't get an error). It is useless in these use cases.

+3
source

All Articles