《Spring Recipes》第四章笔记1:Scripting in Spring
问题
想在Spring中使用JRuby、Groovy、BeanShell等脚本语言。
解决方案
Spring运行用户使用Spring支持的脚本语言实现bean,和配置使用Java实现的bean没有区别。
例:
1、假设需要实现一个计算利润的应用,定义了一个接口InterestCalculator:
public interface InterestCalculator {
public void setRate(double rate);
public double calculate(double amount, double year);
}
2、由于计算利润的策略太多,而且变化太快,所以使用Java实现的话,用户必须不断修改实现,然后recompile、repackage、redeploy。此时,如果使用脚本进行实现,就可以动态修改,不需要recompile、repackage、redeploy。在Spring中使用脚本,需要引入lang schema:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-3.0.xsd">
...
</beans>
Spring2.5开始,支持三种脚本:JRuby、Groovy、BeanShell。
假设Interest = Amount x Rate x Year。
3、使用JRuby。
(1)创建SimpleInterestCalculator.rb,实现InterestCalculator接口。
class SimpleInterestCalculator
def setRate(rate)
@rate = rate
end
def calculate(amount, year)
amount * year * @rate
end
end
SimpleInterestCalculator.new
(2)在配置文件中配置SimpleInterestCalculator.rb。因为使用了JRuby脚本,所以需要使用<lang:jruby>元素,
script-source属性指定了JRuby脚本的位置,script-interfaces指定了脚本实现的接口。
使用<lang:property>元素对脚本中的属性进行注入。
<lang:jruby id="interestCalculator"
script-source="classpath:com/apress/springrecipes/interest/SimpleInterestCalculator.rb"
script-interfaces="com.apress.springrecipes.interest.InterestCalculator">
<lang:property name="rate" value="0.05" />
</lang:jruby>
(3)和使用普通bean一样使用JRuby实现的bean。
ApplicationContext context =new ClassPathXmlApplicationContext("beans.xml");
InterestCalculator calculator =(InterestCalculator) context.getBean("interestCalculator");
System.out.println(calculator.calculate(100000, 1));
4、使用Groovy。
(1)创建SimpleInterestCalculator.groovy,实现InterestCalculator接口。
import com.apress.springrecipes.interest.InterestCalculator;
class SimpleInterestCalculator implements InterestCalculator {
double rate
double calculate(double amount, double year) {
return amount * year * rate
}
}
(2)在配置文件中使用<lang:groovy>元素进行配置。因为 SimpleInterestCalculator.groovy中指定了实现的接口,所以配置文件中无需实现的接口。
<lang:groovy id="interestCalculator"
script-source="classpath:com/apress/springrecipes/interest/SimpleInterestCalculator.groovy">
<lang:property name="rate" value="0.05" />
</lang:groovy>
5、使用BeanShell。
(1)创建SimpleInterestCalculator.bsh,实现InterestCalculator接口。
double rate;
void setRate(double aRate) {
rate = aRate;
}
double calculate(double amount, double year) {
return amount * year * rate;
}
(2)在配置文件中使用<lang:bsh>元素进行配置。
<lang:bsh id="interestCalculator"
script-source="classpath:com/apress/springrecipes/interest/SimpleInterestCalculator.bsh"
script-interfaces="com.apress.springrecipes.interest.InterestCalculator">
<lang:property name="rate" value="0.05" />
</lang:bsh>