这是否可能将 Spring Boot 的 @Value 与 javax.validation.constraints 结合使用?

huangapple go评论71阅读模式
英文:

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

问题

以下是翻译好的内容:

我想要在 application.properties 文件中验证数值。
我使用 @Value 进行注入,同时在一个被 @Configuration 注解的类中,对方法参数使用 @NotBlank 进行验证。

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

我已经添加了 hibernate-validatorhibernate-validator-annotation-processor 属性。使用的是 Spring 2.2.0.RELEASE 版本。

但是这并未生效。数值被注入,但未被验证。我漏掉了什么?

英文:

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?

答案1

得分: 1

添加 @Validated 到你的配置类中。

@Configuration
@Validated
public class MyConfig {

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

        ...
    }

}
英文:

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

        ...
    }

}

huangapple
  • 本文由 发表于 2020年5月30日 05:34:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/62094894.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定