Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

spring - @Autowired HttpServletRequest vs passing as parameter - best practice

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

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

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

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...