spring 中使用 groovy 动态 bean

spring 中使用 groovy 动态 bean

 

原文出处: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.  * @author chenlb 2009-4-7 下午02:04:38 
  7.  */  
  8. public interface Hello {  
  9.   
  10.     String say(String name);  
  11. }  

2、groovy 实现:

  1. package com.chenlb.groovy;  
  2.   
  3. class GroovyHello implements Hello {  
  4.   
  5.     def blog;  
  6.   
  7.     String say(String name) {  
  8.         return "Hello ${name}@${blog}"  
  9.     }  
  10.   
  11.     void setUrl(String blog) {  
  12.         this.blog = blog;  
  13.     }  
  14. }  

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值