我有一个类,它将有一个必须一个接一个地执行的命令列表。命令可能会重复,我不想为每个Command创建一个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调用构造函数?
答案 0 :(得分: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>