springspring-mvcspring-bootspring-bean

Access a request scoped Bean in Service


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

How to access this beans in a @Service which is kind of an application scoped singleton?

The reason for this is, because I have a custom object RequestContext with some request metadata (mostly informations from custom httpHeaders). For know, i pass this object as parameter to each method on each service, which is a lot of boilerplate code.


Solution

  • 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 singleton, 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