JSR-303将语言环境注入自定义验证器

时间:2011-10-07 14:14:59

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

我正在使用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注释来验证邮政编码。但由于邮政编码在不同的国家/地区有不同的格式,我很好奇是否可以将当前的区域设置放入验证器。

1 个答案:

答案 0 :(得分:5)

不是通过注射,但静态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" />
相关问题