简体   繁体   中英

Request scoped beans in Spring HttpRequestHandler

I have followed the suggestion here -> How to connect HttpServlet with Spring Application Context in web.xml to allow access to spring beans in a servlet. It seems to work fine for singleton beans, however I need to access request-scoped beans in my handleRequest() method.

As-is, request scoped beans can't be wired in to the HttpRequestHandler, as it is singleton scoped and as such there is a mis-match of scopes.

I tried making my HttpRequestHandler a request-scoped bean, however this still only ever resulted in a single bean. ie a new instance was not injected for each request. I can only assume that somehow the mechanism employed by org.springframework.web.context.support.HttpRequestHandlerServlet is not allowing a new instace for each request.

My workaround is to get the bean directly from the application context inside the handleRequest method, eg

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

but ideally I'd just like to have the request scoped bean injected in for me.

Any suggestions?

In order to inject a "request" scope or "session" scope bean into a singleton bean, use <aop:scoped-proxy/>

Eg:

<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>

Hope this works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM