可以通过两种不同的方式获得LocaleResolver实例:
RequestContext:RequestContextUtils.getLocaleResolver(request)或@Autowired LocaleResolver localeResolver但是哪种方法更好呢?
背景/背景:
我已经实现了一个定制的变化地区变化拦截器。这是一个HandlerInterceptor,它的工作方式有点像普通的LocaleChangeInterceptor,它使用注入的方式来获得LocaleResolver。啊,真灵。
但今天我更仔细地看了一下LocaleChangeInterceptor。我注意到他们没有注入LocaleResolver,而是从请求上下文(RequestContextUtils.getLocaleResolver(request))*获得它们。
现在,我有点担心,当我通过注入LocaleResolver HandlerInterceptor 获得时,是否忽略了的一个陷阱或类似的东西--有什么想法吗?
LocaleResolverLocaleChangeInterceptorRequestContext* http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html保存一个LocaleResolver实例(通过注入或自创建获得),并将它们放入每个请求的每个请求上下文中。
发布于 2014-02-14 19:15:57
我不认为有什么陷阱。
RequestContextUtils.getLocaleResolver(HttpServletRequest)被实现为
public static LocaleResolver getLocaleResolver(HttpServletRequest request) {
return (LocaleResolver) request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
}换句话说,它是从HttpServletRequest属性获得的。DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE的使用给了我们一个提示,即DispatcherServlet可能正在设置它。它的initLocaleResolver()方法实现为
private void initLocaleResolver(ApplicationContext context) {
try {
this.localeResolver = context.getBean(LOCALE_RESOLVER_BEAN_NAME, LocaleResolver.class);
if (logger.isDebugEnabled()) {
logger.debug("Using LocaleResolver [" + this.localeResolver + "]");
}
}
catch (NoSuchBeanDefinitionException ex) {
// We need to use the default.
this.localeResolver = getDefaultStrategy(context, LocaleResolver.class);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate LocaleResolver with name '" + LOCALE_RESOLVER_BEAN_NAME +
"': using default [" + this.localeResolver + "]");
}
}
}因此,它从上下文中获取它的LocaleResolver,或者通过某些默认配置生成它,即。DispatcherServlet.properties资源
总之,如果您声明一个LocaleResolver bean,那么使用@Autowired注入它和从RequestContextUtils.getLocaleResolver(request)获取它都会得到相同的实例。参见DispatcherServlet#doService(..)方法的
[...]
request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
[...]LocaleChangeInterceptor使用static实用程序,因为它不是Spring意义上的bean。它是一个Spring组件,不一定是WebApplicationContext的一部分,因此不属于它的生命周期。不能注射任何东西。
https://stackoverflow.com/questions/21777193
复制相似问题