《Spring Recipes》第四章笔记2:Injecting Spring Beans i...

《Spring Recipes》第四章笔记2:Injecting Spring Beans into Scripts


问题


需要将Spring中的bean注入到脚本中。

解决方案

使用Setter注入的方式将bean注入到脚本中。

例:假设接口InterestCalculator中使用了RateCalculator接口的实现,InterestCalculator使用脚本实现。
1、定义接口RateCalculator,并实现。
public interface RateCalculator {
public double getAnnualRate();
public double getMonthlyRate();
public double getDailyRate();
}

public class FixedRateCalculator implements RateCalculator {
    private double rate;
    public void setRate(double rate) {
        this.rate = rate;
    }
    public double getAnnualRate() {
        return rate;
    }
    public double getMonthlyRate() {
        return rate / 12;
    }
    public double getDailyRate() {
        return rate / 365;
    }
}

2、注册FixedRateCalculator。
<bean id="rateCalculator" class="com.apress.springrecipes.interest.FixedRateCalculator">
    <property name="rate" value="0.05" />
</bean>


3、定义接口InterestCalculator。
public interface InterestCalculator {
    public void setRateCalculator(RateCalculator rateCalculator);
    public double calculate(double amount, double year);
}


使用JRuby

实现InterestCalculator接口:
class SimpleInterestCalculator
    def setRateCalculator(rateCalculator)
        @rateCalculator = rateCalculator
    end
    def calculate(amount, year)
        amount * year * @rateCalculator.getAnnualRate
    end
end

配置文件:
<lang:jruby id="interestCalculator" script-source="classpath:com/apress/springrecipes/interest/
SimpleInterestCalculator.rb"
script-interfaces="com.apress.springrecipes.interest.InterestCalculator">
    <lang:property name="rateCalculator" ref="rateCalculator" />
</lang:jruby>


使用Groovy

实现InterestCalculator接口:
class SimpleInterestCalculator implements InterestCalculator {
    RateCalculator rateCalculator
    double calculate(double amount, double year) {
        return amount * year * rateCalculator.getAnnualRate()
    }
}

配置文件:
<lang:groovy id="interestCalculator" script-source="classpath:com/apress/springrecipes/interest/SimpleInterestCalculator.groovy">
    <lang:property name="rateCalculator" ref="rateCalculator" />
</lang:groovy>


使用BeanShell

实现InterestCalculator接口:
RateCalculator rateCalculator;
void setRateCalculator(RateCalculator aRateCalculator) {
    rateCalculator = aRateCalculator;
}
double calculate(double amount, double year) {
    return amount * year * rateCalculator.getAnnualRate();
}

配置文件:
<lang:bsh id="interestCalculator" script-source="classpath:com/apress/springrecipes/interest/SimpleInterestCalculator.bsh"
script-interfaces="com.apress.springrecipes.interest.InterestCalculator">
    <lang:property name="rateCalculator" ref="rateCalculator" />
</lang:bsh>





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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值