Kraken
Kraken

Reputation: 24233

ConversionNotSupportedException from String to Custom Class

My config file has the following 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>

And my class MyClass is

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;
}


}

Why am I getting

Cannot convert value of type [java.lang.String] to required type [com.example.otherclasses.Other] for property 'client': no matching editors or conversion strategy found

Upvotes: 0

Views: 131

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 149155

The error is pretty self explainatory. Your setter needs an Other object and you pass it the string "com.example.otherclass.Other". Spring has some default converters, and could convert if to a Class object but not to an Other object.

If all you want is to initialize client attribute with a new Other object, you can use an anonymous(*) inner bean :

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

(*) in fact, the bean will be given a name by Spring, but it is called anonymous since you normally cannot use it by name (you do not know the name).

Upvotes: 1

JSK NS
JSK NS

Reputation: 3446

You are setting the value of client to the string com.example.otherclass.Other.

You need to do something like:

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

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

Upvotes: 2

Related Questions