【问题标题】:Request scoped beans in Spring HttpRequestHandler在 Spring HttpRequestHandler 中请求范围 bean
【发布时间】:2012-11-05 01:57:13
【问题描述】:

我已经按照here -> How to connect HttpServlet with Spring Application Context in web.xml 的建议允许访问 servlet 中的 spring bean。对于单例 bean,它似乎工作得很好,但是我需要在我的 handleRequest() 方法中访问请求范围的 bean。

按原样,请求范围的 bean 不能连接到 HttpRequestHandler,因为它是单例范围的,因此范围不匹配。

我尝试让我的 HttpRequestHandler 成为一个请求范围的 bean,但是这仍然只会产生一个 bean。即没有为每个请求注入一个新实例。我只能假设 org.springframework.web.context.support.HttpRequestHandlerServlet 采用的机制不允许为每个请求创建一个新实例。

我的解决方法是直接从 handleRequest 方法中的应用程序上下文获取 bean,例如

Calendar localNow = (Calendar) applicationContext.getBean("now");

但理想情况下,我只想为我注入请求范围的 bean。

有什么建议吗?

【问题讨论】:

    标签: java spring servlets


    【解决方案1】:

    要将“请求”范围或“会话”范围 bean 注入单例 bean,请使用 <aop:scoped-proxy/>

    例如:

    <bean id="singletonClass" class="com.app.SingletonClass">
    <property name="requestScopeInstance" ref="requestScopeInstance">
    </bean>
    
    <bean id="requestScopeInstance" class="com.app.RequestScopeInstance scope="session">
    <aop:scoped-proxy/>
    </bean>
    

    希望这行得通。

    【讨论】:

      猜你喜欢
      • 2013-01-21
      • 2011-08-15
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      相关资源
      最近更新 更多