简体   繁体   English

Spring会话范围的bean作为原型bean中的依赖项?

[英]Spring session-scoped beans as dependencies in prototype beans?

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. 如果要将(例如)HTTP请求作用域bean注入另一个bean,则必须注入AOP代理来代替作用域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. 也就是说,您需要注入一个代理对象,该对象公开与范围对象相同的公共接口,但也可以从相关范围(例如,HTTP请求)检索真实的目标对象,并将方法调用委托给真实对象。

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. 这里, userManager bean的范围是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? 所以,我想知道这个代理事物是否适用于单例范围的bean,也就是说,如果你想将web-scoped bean注入单例bean,或者它也适用于原型bean? For example, if userManager was scoped as prototype? 例如,如果userManager的范围是原型?

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. 我问这个是因为我看到一些代码在不使用aop-proxy的情况下将会话范围的bean注入到原型中,但我不确定这是否正确...特别是那些在某些web-app中的DAO bean,作用域作为会话 ,它们被注入到原型范围的控制器中,用于多用户环境。 Is this the right way to go? 这是正确的方法吗? How in general should be DAO/Service beans scoped in web-app environment? 一般来说,应该如何在web-app环境中使用DAO / Service bean?

Any idea would be appreciated. 任何想法将不胜感激。

You can always inject a bean of wider scope (eg a singleton) into a bean of narrower scope (eg a session-scoped bean), but to it the other way around, you need a scoped-proxy. 您总是可以将范围更广的bean(例如单例)注入到更窄范围的bean中(例如,会话范围的bean),但反过来说,您需要一个范围代理。

So your example of injecting a session-scoped bean into a prototype-scoped bean is fine, because session-scope is "wider" than prototype-scope. 因此,将会话范围的bean注入到原型范围的bean中的示例很好,因为会话范围比原型范围“更宽”。

If you get it wrong, then Spring will tell you. 如果你弄错了,那么Spring会告诉你的。 If it doesn't complain, then you don't need it. 如果它没有抱怨,那么你不需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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