Spring session-scoped beans as dependencies in prototype beans?

Less picture Less · Mar 11, 2011 · Viewed 8.6k times · Source

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.

Answer

skaffman picture skaffman · Mar 11, 2011

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.