《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>