Autowiring request scoped beans into application scoped beans

前端 未结 3 822
孤独总比滥情好
孤独总比滥情好 2021-02-08 15:17

Is it possible to autowire a request scoped bean into an application scoped bean. i.e

I have a class RequestScopedBean:

class RequestScopedBean {
   ....         


        
相关标签:
3条回答
  • 2021-02-08 15:44

    The exception above suggests that you have not correctly configured Spring for the provision of request scoped beans.

    You need to add this to your web.xml as described in the docs here:

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
      </listener>
    

    However, there is more to your question than just configuration. You are attempting to inject a request scoped bean into a singleton scoped bean. Spring resolves dependencies and instantiates singletons when the DI container starts. This means that ApplicationScopedBean will only be created once (at this point there will be no request in flight and so the autowiring will most likely fail).

    If you were using a prototype scoped bean instead of request scoped you'd have to consider a way of suppling the singleton scoped bean with a fresh instance everytime it was used. The approaches for this are described in the Method Injection chapter of the Spring docs.

    0 讨论(0)
  • 2021-02-08 15:50

    You have to mark your requestScopedBean as a scoped proxy also, this way Spring will inject in a proxy for requestScopedBean and in the background manage the scope appropriately.

    <bean id="requestScopedBean" class="RequestScopedBean" scope="request">  
        <aop:scoped-proxy/>
    </bean>
    

    More here

    0 讨论(0)
  • 2021-02-08 16:02

    @Airwavezx the annotation equivalent is the followinng:

    @Scope( value = SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS )
    
    0 讨论(0)
提交回复
热议问题