gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:45:41 27 4
gpt4 key购买 nike

我多次阅读有关此主题的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com