2011-10-18 42 views
2

我在我的應用程序的context.xml下面這個簡單的表達式:簡單的Spring EL表達式不起作用;錯誤TypeMismatchException

<bean id="instrument" class="com.ustunozgur.Instrument" init-method="initialize" scope="prototype"> 
<property name="age" value="#{4}"/> 
<property name="name" value="Violin"/> 

的儀器類是一個簡單的POJO。然而,它拋出以下錯誤:

[ERROR] ...nested exception is org.springframework.beans.TypeMismatchException: 
Failed  to convert property value of type 'java.lang.String' to required type 
'int' for  property 'age'; nested exception is java.lang.NumberFormatException: For input string: 
"{4}" -> 

這裏是最初的豆聲明在我的xml:

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"> 

可能是什麼問題呢?我在我的pom.xml中包含了spring-core,spring-expression,spring-context。我沒有通過代碼進行任何配置;所有的配置都是通過xml完成​​的。

PS:這是一個命令行應用程序,它可以是罪魁禍首嗎?

PPS:下面的代碼工作的,因此它似乎只是被忽略XML中的SPEL:

ExpressionParser parser = new SpelExpressionParser(); 
    Expression exp = parser.parseExpression("'Hello World'"); 
    String message = (String) exp.getValue(); 

這裏是我的完整應用程序的context.xml和pom.xml中:http://paste.pocoo.org/show/494260/http://paste.pocoo.org/show/494262/

+0

你確定你是春天的正確版本下運行?作爲CLI應用程序並不重要。 –

+0

我的所有工件都引用了Spring 3.0.5版本。我使用Maven建立了項目,所以我猜它運行的是Spring的正確版本。也許我的XML中的XML名稱空間是舊的? – ustun

+0

我已經添加了一個PPS,從代碼作品調用的SPEL。所以我認爲我的xml配置有問題。 – ustun

回答

6

請確保您使用ApplicationContext而不是BeanFactoryBeanFactory不支持ApplicationContext的一些高級功能,包括Spring EL。

參見:

+0

非常感謝!我使用的是過時的教程,看起來像Spring 2.5。 – ustun

+0

啊,以爲我瘋了 - 我從來沒有使用BeanFactory,可能有一系列我從未見過的問題。 –

1

對於簡單的數字屬性,您不需要表達式語言。數字到字符串的轉換由默認的屬性編輯器處理。

<property name="age" value="4"/> 
+0

謝謝。是的,我知道字面值正常工作,我只是試着看它是否有效,這就是爲什麼。 – ustun