java 当 bean 具有可变参数构造函数时,如何 XML 配置 Spring bean 以进行构造函数注入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/751400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 13:38:10  来源:igfitidea点击:

How to XML configure Spring bean for constructor injection when bean has varargs constructor

javaspring

提问by Jen S.

Is there a way to write a Spring bean in XML so that it uses constructor injection when that constructor has a varargs parameter type? IE, is there a way to specify an array the way you can specify a list?

有没有办法用 XML 编写 Spring bean,以便在构造函数具有可变参数类型时使用构造函数注入?IE,有没有办法像指定列表一样指定数组?

For instance:

例如:

class MyClass {
    MyClass(String... args) {
        // rest omitted
    }
}

回答by dfa

since argsis an array of Stringyou can use <list>:

因为args是一个String你可以使用的数组<list>

 <bean name="myBean" class="MyClass">
    <constructor-arg>
        <list>
            <value>111</value>
            <value>222</value>
            <value>333</value>
            <value>444</value>
        </list>
    </constructor-arg>
</bean>