Access a request scoped Bean in Service

前端 未结 1 1353
别那么骄傲
别那么骄傲 2021-02-11 07:20

I have a regular bean, which is either (a) @Scope(\"request\") or (b) placed in a HttpServletRequest via Filter/ Interceptor.

How to access thi

相关标签:
1条回答
  • 2021-02-11 08:08

    As long as the bean is declared as request scope, Spring will take care of the rest.

    @Bean
    @Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
    public RequestContext requestContext() {
        return new RequestContext();
    }
    

    Access the bean in the usual way, just autowire it.

    @Autowired
    private RequestContext requestContext;
    

    The Service bean will be a sigleton but under the covers the RequestContext bean is attached to the thread so you will get a different instance each time a method is called.

    NOTE YOU MUST HAVE A WEB CONTEXT, i.e. RUNNING A WEB SERVER/WEB APP

    0 讨论(0)
提交回复
热议问题