《Spring Recipes》第四章笔记4:Defining Script Sources ...

本文介绍了在Spring框架中如何使用内联脚本定义简单的利息计算器,包括JRuby、Groovy和BeanShell三种脚本语言的应用示例。

《Spring Recipes》第四章笔记4:Defining Script Sources Inline


问题


脚本内容很少,不需要单独写入脚本文件中。

解决方案


使用<lang:inline-script>元素定义脚本。

使用JRuby

<lang:jruby id="interestCalculator"
script-interfaces="com.apress.springrecipes.interest.InterestCalculator">
    <lang:inline-script>
        <![CDATA[
            class SimpleInterestCalculator
                def setRateCalculator(rateCalculator)
                    @rateCalculator = rateCalculator
                end
                def calculate(amount, year)
                    amount * year * @rateCalculator.getAnnualRate
                end
            end
            SimpleInterestCalculator.new
        ]]>
    </lang:inline-script>
    <lang:property name="rateCalculator" ref="rateCalculator" />
</lang:jruby>


使用Groovy

<lang:groovy id="interestCalculator">
    <lang:inline-script>
        <![CDATA[
            import com.apress.springrecipes.interest.InterestCalculator;
            import com.apress.springrecipes.interest.RateCalculator;
            class SimpleInterestCalculator implements InterestCalculator {
                RateCalculator rateCalculator
                double calculate(double amount, double year) {
                    return amount * year * rateCalculator.getAnnualRate()
                }
            }
        ]]>
</lang:inline-script>
<lang:property name="rateCalculator" ref="rateCalculator" />
</lang:groovy>


使用BeanShell

<lang:bsh id="interestCalculator"
script-interfaces="com.apress.springrecipes.interest.InterestCalculator">
    <lang:inline-script>
        <![CDATA[
            import com.apress.springrecipes.interest.RateCalculator;
            RateCalculator rateCalculator;
            void setRateCalculator(RateCalculator aRateCalculator) {
                rateCalculator = aRateCalculator;
            }
            double calculate(double amount, double year) {
                return amount * year * rateCalculator.getAnnualRate();
            }
        ]]>
</lang:inline-script>
<lang:property name="rateCalculator" ref="rateCalculator" />
</lang:bsh>


注意:由于脚本中可能会出现XML关键字,所以需要使用<![CDATA[ ]]>将脚本内容包围起来。


转载于:https://my.oschina.net/pkpk1234/blog/59657

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值