0

我有一个类,它将有一个命令列表,它必须一个接一个地执行。命令可能会重复,我不想为每个命令创建一个 bean。

我的想法是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="parent" class="Parent">
    <property name="commands">
        <list value-type="Command">
            <value>OneCommand</value>
            <value>OtherCommand</value>
            <value>OneCommand</value>
        </list>
    </property>
</bean>
</beans>

对于每个值,都会调用类的构造函数并将新的 Command 对象添加到列表中。

问题是,当我使用该 xml 文件运行测试时,出现以下异常:

...

Caused by: java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [org.fideliapos.middleoffice.provisioning.ProvisioningCommand] for property 'commands[0]': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:231)
at org.springframework.beans.TypeConverterDelegate.convertToTypedCollection(TypeConverterDelegate.java:520)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:173)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:447)
... 42 more

我究竟做错了什么?如何让 spring 调用构造函数?

4

1 回答 1

1

您可以创建一个实现类PropertyEditorSupport,以便 Spring 知道如何从 String 转换为您的自定义域对象。

例子:

public class CommandPropertyEditor extends PropertyEditorSupport {
  public void setAsText(String text) {
    // create a command from the given text
    Command command = Command.createFromString(text);
    setValue(command);
  }
}

然后在 Spring 中引用它:

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
  <property name="customEditors">
    <map>
      <entry key="Command" value="CommandPropertyEditor"/>
    </map>
  </property>
</bean>
于 2012-10-25T15:55:44.903 回答