Spring会话范围的Bean是否作为原型Bean中的依赖项? [英] Spring session-scoped beans as dependencies in prototype beans?

查看:156
本文介绍了Spring会话范围的Bean是否作为原型Bean中的依赖项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我多次阅读了有关此主题的spring文档,但是我仍然不清楚某些事情. 文档状态:

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

如果要将(例如)HTTP请求范围的bean注入另一个bean,则必须注入AOP代理来代替范围的bean.也就是说,您需要注入一个代理对象,该代理对象公开与范围对象相同的公共接口,但还可以从相关范围(例如,HTTP请求)中检索实际的目标对象,并将委托方法调用到实际对象上

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.

配置示例如下:

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

在这里, userManager bean的作用域为单例.因此,我想知道此代理对象是否仅适用于应用于单例范围的bean,也就是说,是否要将Web范围的bean注入单例bean,或者它也适用于原型bean?例如,如果 userManager 的作用域是原型?

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?

我之所以这样问,是因为我看到一些代码,这些代码将会话范围的Bean注入到没有aop-proxy的原型中,但是我不确定这是否正确...特别是在某些Web-应用程序,范围为 session ,并将它们注入到原型范围内的控制器中,用于多用户环境.这是正确的方法吗?一般而言,DAO/Service Bean在Web应用程序环境中应如何划分范围?

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.

推荐答案

您始终可以将范围更广的bean(例如,单例)注入范围更窄的bean(例如,会话范围的bean),但是对此否则,您需要使用作用域代理.

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.

因此,将会话范围的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.

如果弄错了,Spring会告诉您.如果它没有抱怨,那么您就不需要它.

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

这篇关于Spring会话范围的Bean是否作为原型Bean中的依赖项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆