Reputation: 3650
It's weird for me. I have below code:
@Controller
public class MyTestController {
@Autowired
private HttpServletRequest request;
@RequestMapping("/print/")
public String PrintInfo() throws Exception {
Thread.sleep(5000);
System.out.println("name:" +request.getParameter("name"));
System.out.println("hashcode:" +request.hashCode());
return "testpage";
}
}
I visited below url at the same time:
http://127.0.0.1:8080/MyApp/print/?name=tom
http://127.0.0.1:8080/MyApp/print/?name=mike
It printed:
name:tom
hashcode:2006506443
name:mike
hashcode:2006506443
MyTestContorller is singleton. The request's hashcode is same, this means different requests have the same instance.
But why does the request.getParameter("name")
give me the correct result?
Maybe the getParameter method is only a method which need read data form other object?
I don't know, it confused me. Anybody can explain it?
Upvotes: 1
Views: 673
Reputation: 18194
Excerpt from the official documentation should answer your question:
Scoped beans as dependencies
The Spring IoC container manages not only the instantiation of your objects (beans), but also the wiring up of collaborators (or dependencies). If you want to inject (for example) an HTTP request scoped bean into another bean of a longer-lived scope, you may choose to inject an AOP proxy in place of the scoped bean. That is, you need to inject a proxy object that exposes the same public interface as the scoped object but that can also retrieve the real target object from the relevant scope (such as an HTTP request) and delegate method calls onto the real object.
The request scope is based on a thread-local attribute in RequestContextHolder (initialized for every request by DispatcherServlet
by default).
So your HttpServletRequest
is a dynamic JDK proxy, which upon every method call checks the thread-local attribute to get the real request object and calls it.
The resolvable request dependency itself is registered as a bean as part of the WebApplicationContext
initialization by WebApplicationContextUtils
.
And here is a little bit simplified diagram (everything in the picture is actually a singleton):
Upvotes: 3
Reputation: 2621
I say your MyTestController is singleton but the class which implements HttpServletRequest is not.
Each time when request is received the servlet container in the underlying server will create a new instance for the class which provided the implementation for the HttpServletRequest interface and then the reference of that object will be passed to the MyTestController.
It will be just like passing different parameter to a method each time when calling.
Upvotes: 0