从String到Custom Class的ConversionNotSupportedException

时间:2014-11-14 10:44:31

标签: java spring

我的配置文件有以下bean

<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-2.5.xsd">
<bean id="testBean" class="com.example.MyClass">
    <property name="client" value="com.example.otherclass.Other"></property>
</bean>

我的班级MyClass是

public class MyClass implements MyInterface {
Other client;


@Override
public void doIt() {
    // TODO Auto-generated method stub
    try {
        System.out.println(client.getInfo());
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}


public Other getClient() {
    return client;
}


public void setClient(Other client) {
    this.client = client;
}


}

为什么我

无法将[java.lang.String]类型的值转换为属性&#39;客户端所需的类型[com.example.otherclasses.Other]:找不到匹配的编辑器或转换策略

2 个答案:

答案 0 :(得分:2)

您正在将客户端的值设置为字符串com.example.otherclass.Other

您需要执行以下操作:

<bean id="myOther" class="com.example.otherclass.Other">
</bean>

<bean id="testBean" class="com.example.MyClass">
    <property name="client" ref="myOther"></property>
</bean>

答案 1 :(得分:1)

这个错误非常自我解释。您的setter需要一个Other对象,并将字符串"com.example.otherclass.Other"传递给它。 Spring有一些默认转换器,可以将if转换为Class对象,但不转换为Other对象。

如果您只想使用新的client对象初始化Other属性,则可以使用匿名(*)内部bean:

<bean id="testBean" class="com.example.MyClass">
    <property name="client">
        <bean class="com.example.otherclass.Other"/>
    </property>
</bean>

(*)实际上,bean将由Spring命名,但它被称为 anonymous ,因为你通常不能按名称使用它(你不知道名字)。