Spring session-scoped beans as dependencies in prototype beans?

笑着哭i 提交于 2019-12-03 05:21:42

问题


I read spring docs on this subject several times, but some things are still unclear to me. Documentation states:

If you want to inject (for example) an HTTP request scoped bean into another bean, you must inject an AOP proxy in place of the scoped bean. That is, you need to inject a proxy object that exposes the same public interface as the scoped object but that can also retrieve the real, target object from the relevant scope (for example, an HTTP request) and delegate method calls onto the real object.

Config example is as follows:

<bean id="userPreferences" class="com.foo.UserPreferences" scope="session">
     <aop:scoped-proxy/>
</bean>

<bean id="userManager" class="com.foo.UserManager">
     <property name="userPreferences" ref="userPreferences"/>
</bean>

Here, userManager bean is scoped as singleton. So, I'm wondering if this proxy thing applies only to singleton-scoped beans, that is, if you want to inject web-scoped bean into singleton beans, or it also applies to the prototype beans? For example, if userManager was scoped as prototype?

I'm asking this because I saw some code that injects session-scoped beans into prototypes without aop-proxy, but I'm not sure if this is correct... In particular, those were DAO beans in some web-app, scoped as session, and they were injected into prototype-scoped controllers, for multi-user environment. Is this the right way to go? How in general should be DAO/Service beans scoped in web-app environment?

Any idea would be appreciated.


回答1:


You can always inject a bean of wider scope (e.g. a singleton) into a bean of narrower scope (e.g. a session-scoped bean), but to it the other way around, you need a scoped-proxy.

So your example of injecting a session-scoped bean into a prototype-scoped bean is fine, because session-scope is "wider" than prototype-scope.

If you get it wrong, then Spring will tell you. If it doesn't complain, then you don't need it.



来源:https://stackoverflow.com/questions/5270867/spring-session-scoped-beans-as-dependencies-in-prototype-beans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!