zoukankan      html  css  js  c++  java
  • 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  */  
     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

  • 相关阅读:
    《构建之法》阅读报告
    教务管理系统类图及数据库E/R图
    设计模式:抽象工厂
    结对项目:四则运算程序测试
    Leetcode笔记之57和为s的连续正数序列
    Leetcode笔记之1103分糖果 II
    Leetcode笔记之199二叉树的右视图
    每日Scrum(9)
    每日Scrum(7)
    每日Scrum(6)
  • 原文地址:https://www.cnblogs.com/sunxucool/p/2801344.html
Copyright © 2011-2022 走看看