5

我们目前正在使用 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 类的设置器如下:-

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 

谁能给我指点如何使它正常工作?

4

1 回答 1

1

看了 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);
于 2016-05-27T07:06:56.077 回答