在spring中动态使用groovy脚本
动态语言和静态语言结合,各自发挥自己的优势。动态语言易于维护,生产效率较高。静态语言性能更好,语法检查等更严格。目前实现的业务系统是java编写的,但是一些业务频繁变化又要求立刻生效,而且业务也比较复杂,一时不好抽象成规整的可复用java代码。于是考虑修改当前业务系统。基础业务和web界面还是用java相关技术实现,将比较动态和逻辑模糊的业务抽取出来,用groovy实现。
java部分和groovy部分分别是独立的工程。groovy修改后可在java系统运行期间立即生效。
通过spring可以很好的的支持上述的需求和技术要求。首先需要在原有spring项目中加入groovy的库,使用maven很简单:
<dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy</artifactId> <version>1.6.2</version> </dependency>
然后,编写java的业务接口类,比如:
package proto; public interface ProtoBusiness { public void doSomething(); }
编写groovy类实现这个接口:
package proto public class ProtoBusinessGroovyImpl implements ProtoBusiness{ public void doSomething(){ println "Hello world" } }
比较关键的是spring的配置文件,文件头部应该增加lang名字空间:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:lang="http://www.springframework.org/schema/lang" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd">
这样下面语法才可以生效:
<lang:groovy id="protoBusiness" refresh-check-delay="1000" script-source="classpath:proto/ProtoBusinessGroovyImpl.groovy"> </lang:groovy>
另外,可以设置默认的延时刷新时间:
<lang:defaults refresh-check-delay=”60000″ />
<lang:groovy id=”protoBusiness” refresh-check-delay=”1000″
script-source=”classpath:proto/ProtoBusinessGroovyImpl.groovy”>
</lang:groovy>
然后,可以在spring mvc的控制器中ioc加入这个protoBusiness:
package proto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class ProtoController { @Autowired private ProtoBusiness protoBusiness; @RequestMapping("/proto.html") public String test() { long time=System.currentTimeMillis(); protoBusiness.doSomething(); System.out.println("耗时:"+(System.currentTimeMillis()-time)); return "proto"; } }
启动web应用,访问这个spring mvc的控制器链接,服务器控制台就会打印信息。如果更改该groovy文件,因为设置了refresh check delay属性,每10秒钟,改动就会在不重启web应用的情况下自动生效。
正式使用时,可以将source=”classpath:proto/ProtoBusinessGroovyImpl.groovy”通过变量改为某个目录下,这样该目录就可以改动后立即生效。或者,更稳妥的方式是,groovy是单独的项目,测试通过后检入版本库。然后服务器上的groovy目录做update更新。
附上原型的maven项目文档。[Download not found]
这篇文章上的评论的 RSS feed TrackBack URI