Configuring RequestContextListener in SpringBoot

前端 未结 1 1697
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 00:07

I have a Spring-Boot application which uses Spring-Security. I have a request scoped bean that I want to autowire into one of my custom Filters in the security filter chain,

相关标签:
1条回答
  • 2020-12-13 01:02

    As detailed in the update/comments, this was caused by my own stupidity.

    Spring-Boot is able to autowire Request/Session scoped beans into filter's that are outside of the DispatcherServlet As per Spring's documentation, we need to add the RequestContextListener or RequestContextFilter to enable this functionality:

    To support the scoping of beans at the request, session, and global session levels (web-scoped beans), some minor initial configuration is required before you define your beans. (This initial setup is not required for the standard scopes, singleton and prototype.) ...

    If you access scoped beans within Spring Web MVC, in effect, within a request that is processed by the Spring DispatcherServlet, or DispatcherPortlet, then no special setup is necessary: DispatcherServlet and DispatcherPortlet already expose all relevant state.

    To handle this, I needed to register a RequestContextListener bean:

    @Bean public RequestContextListener requestContextListener(){
        return new RequestContextListener();
    } 
    

    If you don't register that bean, you will get an error stating that you are trying to access the Request scope outside of DispatcherServlet.

    The problem I experienced(autowired objects just not being injected) was caused by the fact that I was just registering my custom filter as a standard class instance, not a Spring managed bean:

    http.addFilterBefore( new PreAuthFilter(), BasicAuthenticationFilter )
    

    To solve this, I just moved the creation of the PreAuthFilter to a sepearte @Bean method, the @Autowired functionality then worked fine.

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