我正在尝试定义类型为String[]
的Spring bean,现在能够找到一种方法。示例程序如下所示:
@Component("sampleClass")
public class SampleClass {
@Value("#{someArrayId}")
private String[] someArray;
public void doWithArray() {
System.out.println(Arrays.toString(someArray));
}
}
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>
当我运行程序时,我得到以下异常:
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
我有点理解Spring在抱怨什么,但我不知道如何解决它。
感谢是否有人可以提供帮助。
谢谢,NN
答案 0 :(得分:19)
我不知道这是否是出于某种原因,但是这个配置
<util:list id="someArrayId">
<array>
<value>Tiger</value>
<value>Lion</value>
</array>
</util:list>
正在创建一个List
bean,其中包含一个元素,Object[]
中包含两个String
值。
如果您确实想要一个List
,其中包含两个String
值,那么您应该
<util:list id="someArrayId">
<value>Tiger</value>
<value>Lion</value>
</util:list>
在这种情况下,您可以修改要用
注释的字段@Value("#{someArrayId.toArray(new java.lang.String[0])}")
Spring的EL解析器将能够解析它并执行相应的方法,这会将List
转换为String[]
。
或者,删除@Value
注释并添加@Resource
带注释的方法
@Resource(name = "someArrayId")
private void init(List<String> bean) {
this.someArray = bean.toArray(new String[0]);
}
我觉得这个更清洁,因为它更具描述性。
答案 1 :(得分:10)
而不是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>
答案 2 :(得分:5)
试试这个
@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>