当您更改支持您的 PropertyPlaceholderConfigurer 的属性文件时,您需要“刷新”您的应用程序以使更改生效。如果您使用 ConfigurableApplicationContext 作为您的上下文,那么您可以在您的上下文上调用刷新。挑战在于,在 Web 应用程序中,您将依赖于 web.xml 而不是直接依赖于上下文对象,因此刷新以加载新/更新的属性将需要重新启动应用程序......或经历许多不必要的麻烦。考虑以下是 Spring Webflow 应用程序中的示例。通过使用拦截器更新语言环境。:
public class MyLocaleChangeInterceptor extends org.springframework.web.servlet.i18n.LocaleChangeInterceptor {
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
Locale locale = (Locale) WebUtils.getSessionAttribute(request, LOCALE_SESSION_ATTRIBUTE_NAME);
if (locale != null) {
try {
response.setLocale(locale);
} catch (Exception ex) {
response.setLocale(Locale.ENGLISH);
}
} else {
response.setLocale(Locale.ENGLISH);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
super.postHandle(request, response, handler, modelAndView);
}
}
/** https://gist.github.com/jkuipers/3537965 Spring LocaleResolver that uses cookies but falls back to the HTTP Session when cookies are disabled*/
public class MyCookieLocaleResolver extends CookieLocaleResolver {
private SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
@Override
protected Locale determineDefaultLocale(HttpServletRequest request) {
return sessionLocaleResolver.resolveLocale(request);
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
if (locale != null) {
try {
response.setLocale(locale);
} catch (Exception ex) {
response.setLocale(Locale.ENGLISH);
}
} else {
response.setLocale(Locale.ENGLISH);
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
super.setLocale(request, response, locale);
sessionLocaleResolver.setLocale(request, response, locale);
}
@Override
public void setDefaultLocale(Locale defaultLocale) {
sessionLocaleResolver.setDefaultLocale(defaultLocale);
}
}
<!--Then the XML:-->
<bean id="localeChangeInterceptor" class="MyLocaleChangeInterceptor">
<property name="paramName" value="lang"/>
</bean>
<!-- Saves a locale change using a cookie -->
<bean id="localeResolver" class="MyCookieLocaleResolver" >
<property name="defaultLocale" value="en" />
</bean>
<!--Then Spring-webflow specific XML settings:-->
<bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
<property name="order" value="2"/>
<property name="flowRegistry" ref="flowRegistry" />
<property name="interceptors" >
<list>
<ref local="localeChangeInterceptor" />
</list>
</property>
<property name="defaultHandler">
<bean class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />
</property>
</bean>
如果使用 Spring MVC(没有 spring webflow),请参见此处以获得出色的解决方案:Spring MVC LocaleChangeInterceptor annotation based doesn't work
MyKong 也提供了很好的解决方案:http ://www.mkyong.com/spring-mvc/spring-mvc-internationalization-example/