将RuntimeBeanRefrence用于对象列表时的ConversionNotSupportedException

时间:2013-06-27 13:51:26

标签: java spring

我们目前正在使用spring框架并使用以下XML: -

<bean id="A" class="com.foo.baar.A" >
    <property name="attributes">
        <set value-type="com.foo.bar.B">
            <ref bean="X" />
            <ref bean="Y" />
        </set>
    </property>
</bean>

<bean id="X" class="com.foo.bar.X" />
<bean id="Y" class="com.foo.bar.Y" />

其中类X和类Y扩展了B类

A类的setter如下: -

public void setAttributes(List<B> attributes) {
    this.attributes = attributes;
}

现在,我必须删除上面的XML,并按照以下方式以编程方式设置bean: -

List<Object> beanRefrences = new ArrayList<Object>();
for(String attribute : attributes) {
    Object beanReference = new RuntimeBeanReference(attribute);
    beanRefrences.add(beanReference);
}
mutablePropertyValues.add(propertyName, beanRefrences);

使用上面的代码,我收到以下错误: -

nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.util.ArrayList' to required type 'java.util.List' for property 'attributes'; 
nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.springframework.beans.factory.config.RuntimeBeanReference] to required type [com.foo.bar.B] for property 'attributes[0]': no matching editors or conversion strategy found 

有人能指点我如何让它正常工作吗?

1 个答案:

答案 0 :(得分:0)

在看了Spring的BeanDefinitionValueResolver实现后,可以看到传统的普通List是不够的。您需要使用ManagedList

List<Object> beanRefrences = new ManagedList<>();
for(String attribute : attributes) {
    Object beanReference = new RuntimeBeanReference(attribute);
    beanRefrences.add(beanReference);
}
mutablePropertyValues.add(propertyName, beanRefrences);
相关问题