Spring Bean 配置

Spring Beans Configurations

如果我们有

1- 我们将 class A 配置为单例,将子 class B 作为 Class A 配置为原型的成员的案例场景。

2- 另一种情况,与第一种情况相反,我们将 Class A 定义为原型,将 Class B 定义为单例。

当向 classes A 和 B 发出请求时,Spring 容器将如何初始化和处理这两种情况?

请看看这个答案 - Spring session-scoped beans as dependencies in prototype beans?

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.

这适用于您的问题。

  1. 您正在将范围更窄的 bean 注入范围更广的 bean。 (原型比单例窄)。它应该适合你。

  2. 您正在尝试将更宽范围的 bean 注入到更窄范围的 bean 中。您需要使用作用域代理。