groovy是一种动态脚本语言,适用于一些可变、和规则配置性的需求,目前Spring提供ScriptSource接口,支持两种类型,一种是
ResourceScriptSource,另一种是 StaticScriptSource,但是有的场景我们需要把groovy代码放进DB中,所以我们需要扩展这个。
ResourceScriptSource:在 resources 下面写groovy类
StaticScriptSource:把groovy类代码放进XML里
DatabaseScriptSource:把groovy类代码放进数据库中
工程模块为:
ResourceScriptSource
groovy的pom
<dependency> <artifactId>groovy-all</artifactId> <groupId>org.codehaus.groovy</groupId> <version>2.1.9</version> <scope>compile</scope> </dependency>
HelloService接口
package com.maple.resource.groovy; /** * @author: maple * @version: HelloService.java, v 0.1 2020年09月25日 21:26 maple Exp $ */ public interface HelloService { String sayHello(); }
resources下面建groovy实现类
package com.maple.resource.groovy class HelloServiceImpl implements HelloService { String name; @Override String sayHello() { return "Hello $name. Welcome to reso<strong style="color:transparent">本文来源gao@daima#com搞(%代@#码网@</strong>urce in Groovy."; } }
在spring-groovy.xml中配置
<?xml version="1.0" encoding="UTF-8"?> <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.xsd http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd"> <lang:groovy id="helloService" script-source="classpath:groovy/HelloServiceImpl.groovy"> <lang:property name="name" value="maple"></lang:property> </lang:groovy> </beans>
主类 GroovyResourceApplication
package com.maple.resource; import com.maple.resource.groovy.HelloService; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.support.ClassPathXmlApplicationContext; @SpringBootApplication public class GroovyResourceApplication { public static void main(String[] args) { //SpringApplication.run(GroovyResourceApplication.class, args); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-groovy.xml"); HelloService bean = context.getBean(HelloService.class); String sayHello = bean.sayHello(); System.out.println(sayHello); } }
启动并测试
StaticScriptSource