2

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

4

1 回答 1

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" />
于 2011-10-07T21:29:43.823 回答