如何在春季为带有父级的 xml 中定义的 bean 选择构造函数



我正在使用Spring 3.1.0。我试图了解 spring 读取其 xml 文件的方式。我试图理解春天如何处理豆类定义中的模棱两可的条件。

例如

我有Alarm.java

package com.anshbansal.alarm2;
public class Alarm {
    private String type;
    private int volume;
    private int hour;
    public Alarm() {
    }
    public Alarm(String type, int volume, int hour) {
        this.type = type;
        this.volume = volume;
        this.hour = hour;
    }
    public Alarm(String type, int volume) {
        this.type = type;
        this.volume = volume;
    }
    public Alarm(int volume, String type) {
        this.type = type;
        this.volume = volume;
    }
    public void setType(String type) {
        this.type = type;
    }
    public void setVolume(int volume) {
        this.volume = volume;
    }
    public void setHour(int hour) {
        this.hour = hour;
    }
    @Override
    public String toString() {
        return "Alarm{" +
                "type='" + type + ''' +
                ", volume=" + volume +
                ", hour=" + hour +
                '}';
    }
}

我的弹簧 xml 文件alarm2.xml如下。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
       <bean id="propertyRandom" abstract="true">
              <constructor-arg value="23" type="int"/>
       </bean>

       <bean id="alarm1" class="com.anshbansal.alarm2.Alarm" parent="propertyRandom">
              <constructor-arg value="10" type="int"/>
              <constructor-arg value="Ringing" />
       </bean>

</beans>

存在歧义,因为目前还不清楚哪些int将进入音量,哪些将进入小时。如果我打印,我会得到以下内容

Alarm{type='Ringing', volume=23, hour=10}

那么 spring 如何读取 xml 文件来解决要调用哪个构造函数呢?先是父母,然后是豆子?它记录在某处吗?

我知道有一些方法可以将indexname指定为属性,但我也应该知道如何处理这种模棱两可的条件。这就是我问这个问题的原因。

来自 spring 文档,

构造函数参数解析匹配使用参数的 类型。如果构造函数参数中不存在潜在的歧义 一个 Bean 定义,然后是构造函数参数的顺序 在 Bean 定义中定义是这些参数的顺序 在 Bean 存在时提供给相应的构造函数 实例。

我找到了以下答案,它解释了选择构造函数时的弹簧行为。

如果指定一个没有索引的构造函数参数,则最贪婪的 可以满足给定参数的构造函数将是 已调用(按类型匹配参数(。在java.io.File的情况下, 这是文件(字符串父级,字符串子级(构造函数:您的字符串 参数按类型匹配两者,因此算法使用该构造函数。

参考文献 1参考文献 2

从父级继承时,构造函数参数将被合并(与合并属性集合相同(。在您的情况下,合并后子 bean 构造函数参数将是

<constructor-arg value="23" type="int"/>
<constructor-arg value="10" type="int"/>
<constructor-arg value="Ringing" />

对于不明确的方案,请使用索引或构造函数参数名称。

最新更新