Reputation: 201
I am using Spring 3 and I have the following configuration in my 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>
Everything works fine with locales etc.
However, I was wondering if it is possible to inject the locale to a custom validator I have constructed. I have created a @CheckZip
annotation for validating Zip codes. But since zip codes have different formats in different countries I am curious whether I could throw the current locale into the validator.
Upvotes: 2
Views: 2875
Reputation: 10730
Not by injection, but static LocaleContextHolder can help here:
LocaleContextHolder.setLocale(locale); // set locale for your request or based on user settings e.g. inside custom interceptor
and
LocaleContextHolder.getLocale(); // get locale inside your validator
But I'm not sure why you need the locale explicitly, because having a LocaleChangeInterceptor
that should work already:
<!-- 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" />
Upvotes: 5