JSR-303将区域设置注入自定义验证器



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

不是通过注入,但是静态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" />

最新更新