Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How request-scoped bean injection works in Spring

I am aware that there are some similar questions on SO already, but please read on.

I am reading this Stackoverflow question, and in the accepted answer the author proposes the request-scoped bean injection into a singleton @RestController bean with a simple @Autowired. But how can it possibly work? I mean there is only one @RestController bean in the Spring IoC context. And request-scoped bean is by definition bean that is produced per http request basis. Therefore, each and every request that is handled by a controller, possibly concurrently, will have its own RequestContext.

But again PersonController is a single bean in IoC context, what exactly RequestContext would be injected? What if we have 5 concurrent requests on the same controller - what RequestContext will be injected in this case?

Any help will be highly appreciated, thanks in advance.

like image 469
misha2048 Avatar asked Oct 12 '25 16:10

misha2048


1 Answers

At the very high level, you can think that spring will create a AOP proxy around the actual bean instance and will inject this proxy into the controller. Any method invocation on the proxy instance will be intercepted by spring such that it will create or get the actual bean instance to invoke the actual method.

Every scope in spring besides singleton and prototype will be backed by a Scope implementation. In term of request scope , it is RequestScope. To better understand from codes, you can think that whenever you invoke any methods on that request scoped proxy , it will somehow get the actual bean instance by calling RequestScope#get(beanName,objectFactory) which in turn get the bean from the RequestAttributes . The RequestAttributes will be stored in the ThreadLocal such that each thread will have its own instance. If no beans can be retrieved , it will instantiate a new one and store it to the RequestAttributes.

Normally the implementation of RequestAttributes is ServletRequestAttributes. If you look at its source codes , you can then find that the request scoped bean instance is actually stored as an attribute in the HttpServletRequest.

What if we have 5 concurrent requests on the same controller - what RequestContext will be injected in this case?

Servlet container will handle these requests in separate threads. Each thread will has its own ThreadLocal to store its own HttpServletRequest which in turn store its own RequestContext in its attribute. So it is the RequestContext in the ThreadLocal of the thread that is used to process the HTTP request will be injected into the controller.

like image 81
Ken Chan Avatar answered Oct 14 '25 06:10

Ken Chan