Error in using Expression Language in Spring

867 Views Asked by At

Failed to convert property value of type [java.lang.String] to required type [com.spring.first.Item] for property 'item'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] to required type [com.spring.first.Item] for property 'item': no matching editors or conversion strategy found

server.java

package com.spring.first;
public class Server {
    private Item item;
    private String itemName;
    public Item getItem()
    {
        return item; 
    }

    public String getItemName()
    {
        return itemName;
    }
    public void setItem(Item item)
    {
        this.item=item;
    }
    public void setItemName(String str)
    {
        this.itemName=str;
    }
    @Override
    public String toString()
    {
        return "Server [item ="+item+", itemName ="+itemName+"]";
    }
}

Item.java

public class Item {
    private String name;
    private int qty;
    public String getName()
    {
        return name;
    }
    public int getQty()
    {
        return qty;
    }
    public void setName(String name)
    {
        this.name=name;
    }
    public void setQty(int x)
    {
        this.qty=x;
    }
    @Override
    public String toString()
    {
        return "Item [ name ="+name+", Qty ="+qty+"];";
    }

}

My configuration file

<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-3.0.xsd">

<bean id="itemBean" class="com.spring.first.Item">
        <property name="name" value="itemA" />
        <property name="qty" value="10" />
    </bean>
    <bean id="serverBean" class="com.spring.first.Server">
        <property name="item" value="#{itemBean}" />
        <property name="itemName" value="#{itemBean.name}" />
    </bean>

</beans>

I'm using Spring 2.5.6.

2

There are 2 best solutions below

0
On BEST ANSWER

Spring Exression Language (SPEL) was introduced in Spring 3 (refer to the new features introduced in Spring 3), so it is not possible to use SPEL with Spring 2.5.6.

You will need to upgrade your Spring version to at least 3 (the best would be the latest version, which is currently 4.2.2). The configuration as you have it is correct and would work (see SPEL reference).

1
On

Try changing configuration file as follows

<bean id="itemBean" class="com.spring.first.Item">
    <property name="name" value="itemA" />
    <property name="qty" value="10" />
</bean>
<bean id="serverBean" class="com.spring.first.Server">
    <property name="item" ref="itemBean" />
    <property name="itemName" value="itemBean.name" />
</bean>