【问题标题】:Is it possible to combine spring boot @Value with javax.validation.constraints?是否可以将 spring boot @Value 与 javax.validation.constraints 结合使用?
【发布时间】:2020-09-17 13:12:47
【问题描述】:

我想验证 application.properties 中的值。 我使用@Value 进行注入,并使用@NotBlank 来验证使用@Configuration 注释的类中的方法参数。

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

我已经包含了hibernate-validator 和hibernate-validator-annotation-processor 属性。使用 Spring 2.2.0.RELEASE。

它不起作用。该值已注入,但未验证。我错过了什么?

【问题讨论】:

  • 更喜欢@ConfigurationProperties 而不是裸露的@Value,@Valid 在那里工作得很好。 (另外,如果您使用的是 Boot,您通常应该使用各种特定于 Spring 的配置来获得信任,而不是一揽子系统属性。)
  • @chrylis-cautiouslyoptimistic-我不知道 Spring 特定的配置,直到我用谷歌搜索它。 “附录 A. 常见应用程序属性”是我找到的。 ...我使用信任库创建一个 SSL 上下文,然后创建一个 HttpClient,然后是一个 HttpComponentsClientHttpRequestFactory,最后是一个 RestTemplate。这是一种痛苦。也许有更好的方法?
  • 如果你想创建自己的私有的、完全不受管理的 RestTemplate,你可以这样做,但通常你会使用 Boot 中的RestTemplateBuilder。有关您的特定用例的更多详细信息可能会有所帮助。

标签: java spring-boot jsr305


【解决方案1】:

将@Validated 添加到您的配置类中。

@Configuration
@Validated
public class MyConfig {

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

        ...
    }

}

【讨论】:

  • 我错过了@Validated。我以为如果我有一个组件就不需要它,并且我认为@Configuration 隐含组件。此外,我确实让它早早工作,但没有意识到这一点,因为 ConstraintViolationException 距离 UnsatisfiedDependencyException 的堆栈还有很长的路要走。
猜你喜欢
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-07
  • 2015-01-02
  • 2019-02-15
  • 2017-10-09
相关资源
最近更新 更多