@Autowired HttpServletRequest与传递参数-最佳实践 [英] @Autowired HttpServletRequest vs passing as parameter - best practice

查看:350
本文介绍了@Autowired HttpServletRequest与传递参数-最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们定义了一个仅具有@Controller批注的控制器类.

Assume we have defined a controller class which has @Controller annotation only.

在类中,我们定义了private @Autowired HttpServletRequest request;变量.

Inside the class, we have defined private @Autowired HttpServletRequest request; variable.

Spring Controllers是Singleton.当我们在Web应用程序中将HttpServletRequest定义为@Autowired时,会不会有问题?

Spring Controllers are Singleton. When we defined HttpServletRequest as @Autowired in a web-application, will it be an issue?

我从一个网站上了解到,即使它是@Autowired,它也只是为线程变量注入了一个代理.

I read from a web-site that even though it is @Autowired it just injects a proxy for the thread variable.

是真的吗?在多线程环境中,我们可以使用@Autowired还是将HttpServletRequest作为参数传递给控制器​​类中的每个方法都是正确的方法?

Is it true? In a multi-threaded environment can we use @Autowired or passing HttpServletRequest as a parameter to each method in the controller class would be the right approach?

一些网站表示这是一个问题,建议将其作为参数传递,而很少有人说这将是一个问题.

Some websites says it is an issue and suggested to pass as a parameter whereas few say it will be an issue.

我不知道哪一个是正确的.

I don't understand which one is right.

推荐答案

都可以.
@Autowired HttpServletRequest和作为参数传递是相同的事情.

Both are ok.
@Autowired HttpServletRequest and passing as a parameter are the same things.

在将HttpServletRequest传递给响应@RequestMapping函数的调用方法之前,Spring将HttpServletRequest存储到ThreadLocal类型的变量中.

Before passing HttpServletRequest to invocation method responding to @RequestMapping function, Spring stores the HttpServletRequest into a ThreadLocal type variable.

ThreadLocal变量是线程安全的映射,将HttpServletRequest保留在当前线程上下文中. @Autowired HttpServletRequest代理bean从该ThreadLocal变量获取正确的请求.

That ThreadLocal variable is a thread-safe map that keeps HttpServletRequest in the current thread context. The @Autowired HttpServletRequest proxy bean gets the correct request from that ThreadLocal variable.

这篇关于@Autowired HttpServletRequest与传递参数-最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆