@Autowired HttpServletRequest与传递参数-最佳实践 [英] @Autowired HttpServletRequest vs passing as parameter - best practice
问题描述
假设我们定义了一个仅具有@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屋!