首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过RequestContext获得Spring RequestContext,还是通过注入获得Spring?

通过RequestContext获得Spring RequestContext,还是通过注入获得Spring?
EN

Stack Overflow用户
提问于 2014-02-14 10:45:11
回答 1查看 3.3K关注 0票数 1

可以通过两种不同的方式获得LocaleResolver实例:

  • 通过RequestContextRequestContextUtils.getLocaleResolver(request)
  • via注射:@Autowired LocaleResolver localeResolver

但是哪种方法更好呢?

背景/背景:

我已经实现了一个定制的变化地区变化拦截器。这是一个HandlerInterceptor,它的工作方式有点像普通的LocaleChangeInterceptor,它使用注入的方式来获得LocaleResolver。啊,真灵。

但今天我更仔细地看了一下LocaleChangeInterceptor。我注意到他们没有注入LocaleResolver,而是从请求上下文(RequestContextUtils.getLocaleResolver(request))*获得它们。

现在,我有点担心,当我通过注入LocaleResolver HandlerInterceptor 获得时,是否忽略了的一个陷阱或类似的东西--有什么想法吗?

  • @见:LocaleResolver
  • @见:LocaleChangeInterceptor
  • @见:RequestContext

* http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/web/servlet/DispatcherServlet.html保存一个LocaleResolver实例(通过注入或自创建获得),并将它们放入每个请求的每个请求上下文中。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-14 19:15:57

我不认为有什么陷阱。

RequestContextUtils.getLocaleResolver(HttpServletRequest)被实现为

代码语言:javascript
复制
public static LocaleResolver getLocaleResolver(HttpServletRequest request) {
    return (LocaleResolver) request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
}

换句话说,它是从HttpServletRequest属性获得的。DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE的使用给了我们一个提示,即DispatcherServlet可能正在设置它。它的initLocaleResolver()方法实现为

代码语言:javascript
复制
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(..)方法的

代码语言:javascript
复制
[...]
request.setAttribute(LOCALE_RESOLVER_ATTRIBUTE, this.localeResolver);
[...]

LocaleChangeInterceptor使用static实用程序,因为它不是Spring意义上的bean。它是一个Spring组件,不一定是WebApplicationContext的一部分,因此不属于它的生命周期。不能注射任何东西。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21777193

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档