【问题标题】:Override spring bean without an alias that is also the parent覆盖没有别名的spring bean,它也是父级
【发布时间】:2018-12-04 05:50:44
【问题描述】:

我在 module1-spring.xml-

中有一个 bean
<bean id="parent" class="com.Parent"/>

<bean id="service" class="com.Service">
    <property name="parent" ref="parent"/>
</bean>

我想覆盖 module2-spring.xml-

中的 bean
<bean id="child" class="com.Child" parent="parent"/>

我希望 child 在服务中传递,而不是 parent。 如果我将child 别名为parent

<alias id="child" alias="parent"/>

那么 parent 属性将读取 child 而不是 parent bean 并在服务器启动时失败并出现错误-

BeanDefinitionStoreException:带有名称的 bean 定义无效 在类路径资源 [module2-spring.xml] 中定义的“孩子”:不能 解析父 bean 定义“父”。

当它也是孩子的父母时,覆盖父母的正确方法是什么?

【问题讨论】:

  • 不能这样做的任何原因:
  • @Daud :正是我现在正在做的......覆盖'服务'而不是'父'......但我相信必须有一个更优雅的解决方案......毕竟目的是覆盖“父母”而不是“服务”......!!
  • 这将使它成为一个递归循环。可能有使用 xml 排序绕过它的方法,但 IMO,这将是一个糟糕的设计。另外,您想要的不是覆盖,而是别名,通常不鼓励这样做,因为它会导致代码难以理解。一种思考方式是,假设没有 XML 文件,并且您在 Java 中注入了所有依赖项。这种设置在这种情况下有意义吗?也许这会给其他方法提供更多想法
  • 您的 child bean 扩展了 parent 但由于别名,childparent。因此是循环引用,因此它不起作用。
  • @Daud :这恰好发生在我尝试覆盖“服务”时。这确实有道理。现在,我只是简单地将“服务”的整个定义从“模块1”复制到“模块2”并注入“孩子”。

标签: java spring spring-boot dependency-injection overriding


【解决方案1】:

复制 module2 中的 service bean 并注入 child 解决了这个问题。
module2-spring。 xml-

<bean id="service" class="com.Service">
    <property name="parent" ref="child"/>
</bean>

【讨论】:

    【解决方案2】:

    替换&lt;bean id="child" class="com.Child" parent="parent"/&gt;&lt;bean id="child" class="com.Child" /&gt;

    【讨论】:

      猜你喜欢
      • 2022-07-19
      • 2023-01-25
      • 1970-01-01
      • 2016-12-12
      • 2012-11-05
      • 2020-08-07
      • 2022-01-19
      • 2017-07-22
      • 1970-01-01
      相关资源
      最近更新 更多