Search code examples
javaspring-bootjsr305

Is it possible to combine spring boot @Value with javax.validation.constraints?


I would like to validate values in application.properties. I use @Value to inject and @NotBlank to validate the method parameter in a class annotated with @Configuration.

createSslContext(
            @Value("#{systemProperties['javax.net.ssl.trustStore']}") 
            @NotBlank(message = "Truststore is needed") 
            String path)

I have included the hibernate-validator and the hibernate-validator-annotation-processor properties. Using Spring 2.2.0.RELEASE.

It doesn't work. The value is injected, but not validated. What am I missing?


Solution

  • Add @Validated to your configuration class.

    @Configuration
    @Validated
    public class MyConfig {
    
        @Bean
        MyClass createSslContext(
            @Value("#{systemProperties['javax.net.ssl.trustStore']}")
            @NotBlank(message = "Truststore is needed") final
            String path) {
    
            ...
        }
    
    }