gpt4 book ai didi

java - 为什么spring三元表达式得到相反的结果?

转载 作者:行者123 更新时间:2023-12-02 07:37:16 25 4
gpt4 key购买 nike

我正在通过《Spring in Action 第三版》这本书来学习 Spring。

我正在阅读有关 SpEL 内三元表达式的部分:

它写道:

What if you want a SpELexpression to evaluate to one value if a condition is true and a different value otherwise? For example, let’s say that Carl (the Instrumentalist from earlier) wants to play a piano if the song is “Jingle Bells,” but he’ll play a saxo-phone otherwise. In that case, you can use SpEL’s ternary (?:) operator:

 <property name="instrument"
value="#{songSelector.selectSong()=='Jingle Bells'?piano:saxophone}"/>

As you can see, SpEL’s ternary operator works the same as Java’s ternary operator. In this case, the instrumentproperty will be wired with a reference to the pianobean if the song selected is “Jingle Bells.” Otherwise, it’ll be wired with the bean whose IDis saxophone.

我使用以下 xml 实现此功能:

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

</bean>

<bean id="piano"
class="com.springinaction.springidol.Piano" />
<bean id="saxophone"
class="com.springinaction.springidol.Saxophone" />

输出:

Playing Jingle Bells:TOOT TOOT TOOT

这是错误的,应该是:

Playing Jingle Bells:PLINK PLINK PINK

我已经检查测试是否使用了正确的 xml 并获取了正确的 bean,并且乐器的声音是正确的。 (萨克斯管为 TOOT TOOT TOOT,钢琴为 PLINK PLINK PINK)

有什么想法吗?谢谢。

最佳答案

我的猜测是您正在尝试引用尚未设置的属性。即使它是在 XML 中的三元表达式中的引用“之前”设置的,但在计算 SpEL 表达式时,该属性很可能尚未设置。例如,参见this question on Spring setter order .

如果在设置 song 之前设置 instrument,则您所看到的行为是有意义的。

(您可以将日志语句添加到 setter 中以确定经验调用顺序。)

关于java - 为什么spring三元表达式得到相反的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12031973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com