业务背景
通过页面写入SQL, 再通过固定的接口查询, 实现快速开发。因为SQL中需要涉及参数判断来拼接SQL语句,所有此处引入Groovy来实现判断条件的处理。
例如下面的SQL
通过三元表达式判断拼接, 传入了parent_id则只查询它下面的数据
1. 引入依赖
https://github.com/groovy/GMavenPlus/wiki/Examples
复制代码
1
2
3
4
5
6<dependency> <artifactId>groovy-all</artifactId> <groupId>org.codehaus.groovy</groupId> <version>3.0.9</version> <type>pom</type> </dependency>
2. 创建Groovy文件
3. 代码
具体的语法请移步 Groovy的基本语法_会飞的哈士奇的博客-CSDN博客
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49package cn.com.baidu.groovy import javax.script.Bindings import javax.script.Invocable import javax.script.ScriptEngine import javax.script.ScriptEngineManager /** * Groovy动态条件拼接SQL */ class SQLGroovy { // 查找并创建指定脚本引擎 private ScriptEngine engine = new ScriptEngineManager().getEngineByName("groovy"); String executeFunction(Map<String, Object> params, String querySql){ // 初始化Bindings Bindings bindings = engine.createBindings(); if(params != null) { for(Map.Entry<String, Object> map : params.entrySet()) { // 绑定参数 bindings.put(map.getKey(), map.getValue()); // bindings.setVariable(map.getKey(), map.getValue()); } } // 定义groovy脚本中执行方法的名称 String scriptName = "executeSQL"; // 定义groovy脚本内容 String scriptContent = ''' def executeSQL() { def sqlStr = "'''+ querySql + '''"; return sqlStr; } '''; try { // 执行脚本 engine.eval(scriptContent, bindings); // 获取执行结果 Invocable invocable = (Invocable) engine; def result = (String) invocable.invokeFunction(scriptName); return result; } catch (ScriptException | NoSuchMethodException e) { e.printStackTrace(); } return ""; } }
4. 编译
如果此时用maven直接编译,在调用.groovy类的地方会编译不通过,提示找不到符号。
这是因为maven无法编译.groovy类导致的这个问题,.groovy类需要引入maven插件来进行单独编译。
pom文件中引入插件
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39<build> <plugins> <plugin> <groupId>org.codehaus.gmavenplus</groupId> <artifactId>gmavenplus-plugin</artifactId> <version>1.6.1</version> <configuration> <sourceEncoding>UTF-8</sourceEncoding> <sources> <source><!-- cn/com/baidu/groovy则是.groovy文件的路径,配置以后编译的时候就会找这个路径下的.groovy文件 --> <directory>${project.basedir}/src/main/java/cn/com/baidu/groovy</directory> <includes> <include>**/*.groovy</include> </includes> </source> </sources> <testSources> <testSource> <directory>${project.basedir}/src/main/test/cn/com/baidu/groovy</directory> <includes> <include>**/*.groovy</include> </includes> </testSource> </testSources> <!-- 用maven编译时需要加encoding:mvn -Dfile.encoding=UTF-8 compile --> </configuration> <executions> <execution> <goals> <goal>addSources</goal> <goal>addTestSources</goal> <goal>compile</goal> <goal>compileTests</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
执行插件gmaven编译groovy文件
最后
以上就是欣喜萝莉最近收集整理的关于SpringBoot项目Java中集成Groovy敏捷开发语言的全部内容,更多相关SpringBoot项目Java中集成Groovy敏捷开发语言内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复