【问题标题】:Using SpEL to copy references of a beans is not working使用 SpEL 复制 bean 的引用不起作用
【发布时间】:2013-07-04 14:00:15
【问题描述】:

我一直在尝试使用 Spring。我希望通过使用 SpEL 为另一个 bean 复制一个 bean 的值和引用属性。

考虑这个 bean:

<bean id="kenny" class="com.springinaction.springidol.Instrumentalist">
    <property name="song" value="#{'Jingle Bells'}" /> 
    <property name="instrument" ref="piano" /> 
</bean>

我希望将其值复制到另一个bean中,如下所示:

<bean id="carl" class="com.springinaction.springidol.Instrumentalist"> 
    <property name="song" value="#{kenny.song}" /> 
    <property name="instrument" ref="#{kenny.instrument}" /> <-- I GET EXCEPTION OVER HERE

</bean>

但是,我对第二个属性有一个例外,因为它无法复制肯尼的仪器。歌曲被正确复制,没有抛出任何异常

我得到了这个例外:

线程“main”中的异常 org.springframework.beans.factory.BeanCreationException:错误 创建在类路径资源中定义的名称为“carl”的bean [Beans.xml]:无法解析对 bean '#{kenny.instrument}' 的引用 同时设置 bean 属性“仪器”;嵌套异常是 org.springframework.beans.factory.BeanExpressionException:表达式 解析失败;嵌套异常是 org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 6): 找不到字段或属性“仪器” 'com.springinaction.springidol.Instrumentalist' 类型的对象

知道如何复制仪器并将其设置为 id 为“carl”的 bean 吗?

【问题讨论】:

    标签: java spring spring-el spelevaluationexception beancreationexception


    【解决方案1】:

    ref 是对另一个 bean 的引用;在您的情况下,您想使用 kenny bean 的 instrumemt 属性的值。

    你应该使用

     <property name="instrument" value="#{kenny.instrument}" />
    

    这假设Instrumentalist 上有一个getInstrument() 方法。

    【讨论】:

    • 谢谢它的工作。我添加引用的唯一原因是因为 kenny 所指的乐器也是 bean。
    • kenny 属性的来源是 bean 无关紧要;在解决时,该关联丢失 - 您可以使用 ref="piano"value="#{kenny.instrument}
    猜你喜欢
    • 1970-01-01
    • 2011-08-10
    • 2015-10-08
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多