1

I searched for solutions to validate data models in spring in Kotlin. But am not able to. The following is the Tag data class.

data class Tag(@field:NotNull var name: String) {
    lateinit @Id var id: ObjectId
}

I have enabled the configuration to use bean validation

@Configuration
open class ValidatorConfig {
    @Bean
    open fun validator() = LocalValidatorFactoryBean()
}

As per my knowledge, Spring Boot loads all the Bean Configuration automatically. And at runtime, when POSTed with empty Json, proper validation error should have been thrown but the following error is thrown

Instantiation of [simple type, class kagaz.sano.model.Tag] value failed for
JSON property name due to missing (therefore NULL) value for creator parameter 
name which is a non-nullable type\n at [Source:
org.apache.catalina.connector.CoyoteInputStream@66f3b65c; line: 3, column: 1]
(through reference chain: kagaz.sano.model.Tag[\"name\"])
  • Your property is of type String. So Kotlin won't allow you to store null in it, and then let the validator check if it's null or not. You would need String? for that. – JB Nizet Nov 18 '16 at 20:07
  • But when I use String?, the data is stored in the DB without any validation. –  Nov 19 '16 at 02:52
  • Have you made sure that the config was loaded? Where is the code/annotation triggering the validation? – JB Nizet Nov 19 '16 at 06:44
  • Yes the config was loaded. I ran through the list of `beanDefinitionNames` in the context. It was loaded. –  Nov 19 '16 at 08:35

1 Answers1

0

Spring validates objects by inspecting it's fields or properties values. To validate an object you need to first create it. When the json deserializer tries to parse input and create Tag instance it encounters and reports the problem:

Instantiation of [simple type, class kagaz.sano.model.Tag] value failed for JSON property name

In order for Spring Validation to even start its work an instance of object is required - even if it is invalid.

This means that you'll need to allow for json deserializer to create an object in invalid state so that it can be inspected by validator like so:

data class TagDto(@get:NotNull var name: String? = null) {
    @get:NotNull var id: ObjectId? = null
}
miensol
  • 39,733
  • 7
  • 116
  • 112
  • I tried your solution, but when I given an empty POST it just bypasses the validation and stores the record. –  Nov 19 '16 at 10:46
  • @SharadCodes show me your controller method please – miensol Nov 19 '16 at 11:15
  • Apparently the problem was with mongodb. So, I took the solution from [here](http://stackoverflow.com/a/22583492/3236751). Anyways thank you. –  Nov 19 '16 at 11:56