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

《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[ ]]>将脚本内容包围起来。


你可能感兴趣的:(spring)