Java 如何在Spring中定义一个String数组的bean(使用XML配置)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22279020/
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-08-13 14:42:27  来源:igfitidea点击:

How to define a bean of String array in Spring (using XML configuration)

javaspring

提问by Niranjan

I am trying to define a Spring bean of type String[]and now able to find a way to do so. Sample program is shown below:

我正在尝试定义一个 Spring bean 类型String[],现在能够找到一种方法来做到这一点。示例程序如下所示:

@Component("sampleClass")
public class SampleClass {
    @Value("#{someArrayId}")
    private String[] someArray;

    public void doWithArray() {
        System.out.println(Arrays.toString(someArray));
    }
}

Spring XML Configuration

Spring XML 配置

<context:annotation-config />
<context:component-scan base-package="com.demo.spring" />

<util:list id="someArrayId">
    <array>
        <value>Tiger</value>
        <value>Lion</value>
    </array>
</util:list>

When I am running the program, I get following exception:

当我运行程序时,出现以下异常:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sampleClass': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String[] com.demo.spring.SampleClass.someArray; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.util.ArrayList' to required type 'java.lang.String[]'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.Object[]] to required type [java.lang.String]: no matching editors or conversion strategy found

I kind of understand what Spring is complaining, but I don't know how to fix it.

我有点理解 Spring 在抱怨什么,但我不知道如何解决它。

Appreciate if anyone can help.

感谢有人可以提供帮助。

Thanks, NN

谢谢,神经网络

采纳答案by Sotirios Delimanolis

I don't know if this is done for a reason, but this configuration

我不知道这样做是否出于某种原因,但是这种配置

<util:list id="someArrayId">
    <array>
        <value>Tiger</value>
        <value>Lion</value>
    </array>
</util:list>

is creating a Listbean that contains one element, a Object[]with two Stringvalues in it.

正在创建一个List包含一个元素的bean,a 中Object[]包含两个String值。

If you actually wanted a Listwith two Stringvalues in it, you should have

如果你真的想要一个List有两个String值的,你应该有

<util:list id="someArrayId">
    <value>Tiger</value>
    <value>Lion</value>
</util:list>

in which case you could modify your field to be annotated with

在这种情况下,您可以修改要注释的字段

@Value("#{someArrayId.toArray(new java.lang.String[0])}")

Spring's EL resolver will be able to parse it and execute the corresponding method, which will convert the Listto a String[].

Spring的EL解析器将能够分析它并执行相应的方法,这将转换ListString[]

Alternatively, remove the @Valueannotation and add a @Resourceannotated method

或者,删除@Value注释并添加带@Resource注释的方法

@Resource(name = "someArrayId")
private void init(List<String> bean) {
    this.someArray = bean.toArray(new String[0]);
}

I find this cleaner as it's more descriptive.

我觉得这个更简洁,因为它更具描述性。

回答by Evgeniy Dorofeev

try like this

像这样尝试

@Component("sampleClass")
public class SampleClass {
    @Value("#{someArrayId.toArray(new String[0])}")
    private String[] someArray;
    ...

<util:list id="someArrayId">
    <value>Tiger</value>
    <value>Lion</value>
</util:list>

回答by Ahsan Shah

instead of List, just define array. You can also inject it as configuration to make it less ambiguous. Here another point to note is value-typeof array.

而不是List,只需定义数组。您还可以将其作为配置注入,以减少歧义。这里还有一点要注意的是value-type数组。

<bean id="sampleClass" class="somePackage.SampleClass">
    <property name="someArray">
        <array value-type="java.lang.String">
            <value>Tiger</value>
            <value>Lion</value>
        </array>
    </property>
</bean>