【问题标题】:JSR-303 inject locale into custom validatorJSR-303 将语言环境注入自定义验证器
【发布时间】:2011-10-07 14:14:58
【问题描述】:

我使用的是 Spring 3,我的 applicationContext.xml 中有以下配置:

  <bean id="validationMessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
    p:basename="classpath:messages/validation_messages" p:defaultEncoding="UTF-8" p:cacheSeconds="3" />

  <bean id="globalValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
    <property name="validationMessageSource">
      <ref bean="validationMessageSource" />
    </property>
  </bean>

在语言环境等方面一切正常。

但是,我想知道是否可以将语言环境注入到我构建的自定义验证器中。我创建了一个 @CheckZip 注释来验证邮政编码。但是由于邮政编码在不同的国家有不同的格式,我很好奇我是否可以将当前的语言环境放入验证器中。

【问题讨论】:

    标签: java spring spring-mvc bean-validation hibernate-validator


    【解决方案1】:

    不是通过注入,而是静态 LocaleContextHolder 可以在这里提供帮助:

    LocaleContextHolder.setLocale(locale); // set locale for your request or based on user settings e.g. inside custom interceptor
    

    LocaleContextHolder.getLocale(); // get locale inside your validator
    

    但我不确定你为什么需要明确地使用语言环境,因为有一个 LocaleChangeInterceptor 应该已经可以工作了:

    <!-- Declare the Interceptor -->
    <mvc:interceptors>    
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"
              p:paramName="locale" />
    </mvc:interceptors>
    
    <!-- Declare the Resolver -->
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
    

    【讨论】:

      猜你喜欢
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      相关资源
      最近更新 更多