Hi Spring team 👋,
I'm trying to use @Validated in a Kotlin configuration property class like so:
MyAppProperties.kt:
@Validated
@ConstructorBinding
@ConfigurationProperties("my.app")
class MyAppProperties(
@NotBlank
val username: String,
@NotBlank
val password: String,
)
application.properties:
my.app.username=${USERNAME:}
my.app.password=${PASSWORD:}
build.gradle.kts:
implementation("org.springframework.boot", "spring-boot-starter-validation")
The motivation is to ensure that I detect a missing environment variable at startup, but the validation does not seem to apply to constructor arguments (the config object is constructed without any exception thrown).
If I change it to use setters (rather than a constructor):
@Validated
@ConfigurationProperties("my.app")
class MyAppProperties {
@NotBlank
lateinit var hostname: String
@NotBlank
lateinit var username: String
}
The validation will correctly work, but now I lose my immutability guarantee, and the class is more cluttered with lateinit (or, optionally, unnecessary initializers like = "").
Is there any chance that validation could be performed on constructor arguments to enable this more idiomatic use case?
Thanks!
Versions used:
org.springframework.boot:spring-boot:2.6.6
org.springframework.boot:spring-boot-starter-validation:2.6.6
Comment From: wilkinsona
You need to tell Kotlin where the annotations should go in the generated Java class. See https://kotlinlang.org/docs/annotations.html#annotation-use-site-targets for further details. @get:NotBlank should meet Hibernate Validator's needs.
Comment From: Bennett-Lynch
Thanks for the reply @wilkinsona. I don't think that's the problem here though. My provided example will actually validate the getters/setters perfectly fine (without any use-site targets), but it still doesn't allow me to use constructor-based properties (i.e., @ConstructorBinding). Is this a Hibernate Validator limitation? Please consider reopening if it's Spring-related.
Comment From: philwebb
@Bennett-Lynch are you able to attach a sample application that we can debug to see what's going on?
Comment From: spring-projects-issues
If you would like us to look at this issue, please provide the requested information. If the information is not provided within the next 7 days this issue will be closed.
Comment From: spring-projects-issues
Closing due to lack of requested feedback. If you would like us to look at this issue, please provide the requested information and we will re-open the issue.