原文出處:http://blog.chenlb.com/2009/04/spring-use-groovy-dynamic-bean.html
在 spring 中使用 groovy 等動态語言的好處就是:在伺服器上改改或新加個 groovy 檔案就可以有新的功能,不用重新打包并部署。對一些規則性的邏輯處理、動态性強的應用可以 groovy。
示例下在 spring 中使用 groovy,我機子環境 spring 2.5.5, groovy-1.5.7。
1、模拟業務接口:
1 package com.chenlb.groovy;
2
3 /**
4 * 業務模拟接口
5 *
6 */
7 public interface Hello {
8
9 String say(String name);
10 }
2、groovy 實作:
package com.chenlb.groovy;
class GroovyHello implements Hello {
def blog;
String say(String name) {
return "Hello ${name}@${blog}"
}
void setUrl(String blog) {
this.blog = blog;
}
}
3、spring 配置 applicationContext-groovy.xml:
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3 xmlns:lang="http://www.springframework.org/schema/lang"
4 xsi:schemaLocation="
5 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
6 http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd">
7
8 <lang:groovy id="groovyHello" script-source="classpath:com/chenlb/groovy/GroovyHello.groovy">
9 <lang:property name="blog" value="http://blog.chenlb.com"></lang:property>
10 </lang:groovy>
11
12 </beans>
4、運作:
1 package com.chenlb.groovy;
2
3 import org.springframework.context.ApplicationContext;
4 import org.springframework.context.support.FileSystemXmlApplicationContext;
5
6 public class Main {
7
8 public static void main(String[] args) {
9 ApplicationContext context = new FileSystemXmlApplicationContext("classpath:applicationContext-groovy.xml");
10
11 Hello hello = (Hello) context.getBean("groovyHello");
12
13 System.out.println(hello.say("chenlb"));
14 }
15
16 }
結果:
Hello chenlb@http://blog.chenlb.com
要在 spring 中用 groovy,依賴的jar有:antlr-2.7.6.jar、aopalliance.jar、asm-2.2.3.jar、asm-commons-2.2.3.jar、asm-util-2.2.3.jar、groovy-1.5.5.jar在spring 的 lib中可以找到,還有spring-aop-2.5.5.jar。當然也可以把groovy-1.5.5.jar換成groovy-1.5.7.jar