Spring session 范围的bean作为原型(prototype)bean中的依赖项?

标签 spring scope dao javabeans httpsession

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

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-scoped bean注入(inject)单例bean,或者它也适用于原型(prototype)bean?例如,如果 userManager 被限定为原型(prototype)?

我问这个是因为我看到一些代码将 session 范围的 bean 注入(inject)没有 aop-proxy 的原型(prototype)中,但我不确定这是否正确......特别是,那些是某些网络中的 DAO bean-应用程序,范围为 session,它们被注入(inject)到原型(prototype)范围的 Controller 中,用于多用户环境。这是正确的方法吗?一般而言,DAO/Service bean 在 Web 应用环境中的作用域应该如何?

任何想法都将不胜感激。

最佳答案

您始终可以将范围更广的 bean(例如单例)注入(inject)到范围更窄的 bean(例如 session 范围的 bean)中,但反过来,您需要一个范围代理。

因此,您将 session 范围 bean 注入(inject)原型(prototype)范围 bean 的示例很好,因为 session 范围比原型(prototype)范围“更宽”。

如果你弄错了,Spring 会告诉你。如果它不提示,那么你就不需要它。

关于Spring session 范围的bean作为原型(prototype)bean中的依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5270867/

相关文章:

Java - 单击 JButton 将 int 值更改为特定范围内的随机数

java - 实现基本 dao 时,我收到错误 Type of theparameter must be an annotated with @Entity or a collection/array of it

java - Spring-远程基本身份验证

java - 如何使用两个属性作为key的spring缓存

python - 描述当前范围的对象

C++ 为什么我无法使用在声明它的类之外全局声明的枚举?

java - hibernate/Junit 测试 : Data still remain in session even after closing and opening it or cleaning it

java - 程序运行时的 Dropwizard session

java - 如何防止在模板中使用环境变量?

java - 为后台任务替换作用域 session bean