Inject HttpServletRequest into Controller

前端 未结 2 581
南旧
南旧 2020-12-09 18:00

As I know per default are controllers in Spring MVC singletons. HttpServletRequest passed offen to the controller handler method. And its ok, while HttpSe

2条回答
  •  渐次进展
    2020-12-09 18:35

    What happens if inject a reqeust-scoped component into a singleton?

    Try it and you'll get a BeanCreationException¹ during application context initialization. The error message clearly explains why this doesn't happen with HttpServletRequest:

    Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton;

    So obviously HttpServletRequest is a scoped proxy. If you want to use beans of smaller scopes in singletons they have to be proxies. The documentation elaborates about smaller scoped dependencies in Scoped beans as dependencies.

    [1]: unless you didn't change the default behaviour for proxyMode, which is NO or try to inject it with @Lazy. The latter might result into a valid application context but might lead to request scoped beans acting like singletons (e.g. if a request scoped bean is injected into a singleton).

提交回复
热议问题