2

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?

ahoffer
  • 6,347
  • 4
  • 39
  • 68
  • 1
    Prefer `@ConfigurationProperties` to bare `@Value`, and `@Valid` works fine there. (Also, if you're using Boot, you _usually_ should be using the various Spring-specific configurations for trust instead of a blanket system property.) – chrylis -cautiouslyoptimistic- May 29 '20 at 21:37
  • @chrylis-cautiouslyoptimistic-I didn't know about the Spring-specific configs until I googled it. "Appendix A. Common application properties" is what I found. ... I use the trust store to create an SSL Context, then create an HttpClient, then a HttpComponentsClientHttpRequestFactory, and finally a RestTemplate. It's a pain. Maybe there is a better way? – ahoffer May 29 '20 at 23:30
  • If you want to create your own private, completely unmanaged RestTemplate, you can do that, but usually you'll use `RestTemplateBuilder` from Boot. More details about your specific use case might be helpful. – chrylis -cautiouslyoptimistic- May 30 '20 at 01:47

1 Answers1

1

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) {

        ...
    }

}
  • I was missing @ Validated. I thought I didn't need it if I had a component and I thought @ Configuration implied component. Also, I did have it working early but did not realize it because the ConstraintViolationException was a long, long way down the stack from UnsatisfiedDependencyException. – ahoffer May 29 '20 at 23:52