2011-10-07 49 views
1

我使用Spring 3,我有下面的配置,我的applicationContext.xml:JSR-303注入到区域设置自定义的验证

<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> 

一切工作正常的语言环境等

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

回答

4

不注射,但静态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" />