背景
目前工作需要对已有的文件进行参数渲染,以供其他方法调用。打个比方,我现在有一段报文如下:
1 2 3 4 5 6 7
| { "a":"a", "b":"hello kitty", "c":"c", "d":"d", "e":"hello world" }
|
那我需要修改某个或者某些字段的数值,如何做呢 ? 那就轮到模版渲染引擎Beetl出场,然后我们会以链式编程的方式来实现。
链式编程
创建模版
将上面的报文已文件形式报文,放置到resource目录下,命名为example.json。项目结构如图

修改文件内容如下
1 2 3 4 5 6 7
| { "a":"${a}", "b":"hello kitty", "c":"${c}", "d":"${c}", "e":"hello world" }
|
渲染模版
我们的目的是渲染模版,在这里我采用的是java的链式编程方式来实现。要达到这个目的,也就是说通过”实例名.方法名”这样的方式,必须使得实例方法返回的都是它本身。
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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| import org.beetl.core.Configuration; import org.beetl.core.GroupTemplate; import org.beetl.core.Template; import org.beetl.core.resource.ClasspathResourceLoader;
import java.io.IOException; import java.util.HashMap; import java.util.Map;
public class BeetlUtil{
private Template tmp; private BeetlUtil(String fileName) { ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader("json"); Configuration cfg = null; try { cfg = Configuration.defaultConfiguration(); } catch (IOException e) { e.printStackTrace(); } GroupTemplate gt = new GroupTemplate(resourceLoader, cfg); this.tmp = gt.getTemplate(fileName); }
public BeetlUtil bind(Map map) { this.tmp.binding(map); return this; } public BeetlUtil bind(String key, Object obj) { tmp.binding(key, obj); return this; } public String asString() { return tmp.render(); }
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>(16){ { put("c","hello c"); put("d","hello d"); } }; String str = new BeetlUtil("example.json") .bind(map) .bind("a","hello a") .asString(); System.out.println(str); } }
|
打印结果
1 2 3 4 5 6 7
| { "a":"hello a", "b":"hello kitty", "c":"hello c", "d":"hello d", "e":"hello world" }
|