经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
Beetl 源码解析:GroupTemplate 类
来源:cnblogs  作者:腐烂的橘子  时间:2024/4/23 16:14:13  对本文有异议

本文首发于公众号:腐烂的橘子

前言

Beetl 是一款 Java 模板引擎,在公司的项目中大量运用,它的作用是写通用代码时,有一些差异化的逻辑需要处理,这时可以把这些差异化的逻辑写在模板里,程序直接调用,实现了代码的低耦合。

有人问差异化的东西为什么不能通过配置实现?原因是配置只能将一些差异化的值抽离出来,一些复杂的逻辑很难做到。比如有一个类似计算器的界面,里面可以对一些业务字段进行公式计算:

  • 分润 = 利息 * 0.2
  • 分润 = (利息 + 罚息) * 0.1

程序在计算这个表达式前,并不知道表达式的具体内容,只是想由业务传入利息、罚息这些字段上下文信息后,能自动计算出结果。这时使用 Beetl 模板,我们将上面的公式用 Beetl 表达式表示:

  • <%print(interest * 0.2);%>
  • <%print((interest + penalty) * 0.2);%>

代码中就不用感知具体公式内容了,直接写通用逻辑即可:

  1. public static void main(String[] args) throws IOException {
  2. // 用户输入的公式
  3. String formula = "xxxx";
  4. // 计算结果的上下文参数
  5. HashMap param = new HashMap();
  6. // 核心代码
  7. GroupTemplate gt = new GroupTemplate(new StringTemplateResourceLoader(), Configuration.defaultConfiguration(););
  8. Template template = gt.getTemplate(formula);
  9. template.binding(new HashMap());
  10. // ans 就是计算的结果
  11. String ans = template.render();
  12. }

以上就是 Beetl 的基本使用方法,具体可以参考文档,接下来的几篇文章,将对其源码进行解析,如有不合理的地方,欢迎各位大佬批评指正。

核心类 GroupTemplate 源码解析

核心字段定义

GroupTemplate 类核心字段定义如下:

  1. public class GroupTemplate {
  2. /* 模板在运行过程中,class方法,accessory调用等需要的classLoader */
  3. ClassLoader classLoader = Thread.currentThread().getContextClassLoader() != null
  4. ? Thread.currentThread().getContextClassLoader()
  5. : GroupTemplate.class.getClassLoader();
  6. AABuilder attributeAccessFactory = new AABuilder();
  7. ResourceLoader resourceLoader = null;
  8. Configuration conf = null;
  9. TemplateEngine engine = null;
  10. Cache programCache = ProgramCacheFactory.defaulCache();
  11. List<Listener> ls = new ArrayList<Listener>();
  12. // 所有注册的方法
  13. Map<String, Function> fnMap = new HashMap<String, Function>();
  14. // 格式化函数
  15. Map<String, Format> formatMap = new HashMap<String, Format>();
  16. Map<Class, Format> defaultFormatMap = new HashMap<Class, Format>(0);
  17. // 虚拟函数
  18. List<VirtualAttributeEval> virtualAttributeList = new ArrayList<VirtualAttributeEval>();
  19. Map<Class, VirtualClassAttribute> virtualClass = new HashMap<Class, VirtualClassAttribute>();
  20. // 标签函数
  21. Map<String, TagFactory> tagFactoryMap = new HashMap<String, TagFactory>();
  22. ClassSearch classSearch = null;
  23. // java调用安全管理器
  24. NativeSecurityManager nativeSecurity = null;
  25. ErrorHandler errorHandler = null;
  26. Map<String, Object> sharedVars = null;
  27. ContextLocalBuffers buffers = null;
  28. // 用于解析html tag得属性,转化为符合js变量名字
  29. AttributeNameConvert htmlTagAttrNameConvert = null;
  30. //...
  31. }

核心字段解释如下:

  • classLoader: 模板在运行中需要的 ClassLoader
  • attributeAccessFactory: 一个工厂类,为一个特定类的方法生成 AttributeAccess,如果类是 Map,则生成 MapAA;如果类是 List, 则生成 ListAA 等
  • resourceLoader: 资源加载器,根据 GroupTemplate 的 key 获取对应资源的加载器,可以是文件、字符串等
  • conf: 模板配置,核心类,与 Beetl 相关的所有配置
  • engine: 模板引擎,只有一个 createProgram 方法,这个方法可以生成一个用来执行模板的程序
  • programCache: 本地缓存,基于 ConcurrentHashMap 实现
  • ls: 事件的监听器列表,暂时没用

GroupTemplate 核心方法

构造方法

构造方法主要分为三步:

  1. 初始化默认配置
  2. 执行 init() 初始化方法,后面会讲
  3. 初始化资源加载器,实际上就是初始化 resourceLoader
  1. public GroupTemplate() {
  2. try {
  3. this.conf = Configuration.defaultConfiguration();
  4. init();
  5. initResourceLoader();
  6. } catch (Exception ex) {
  7. throw new RuntimeException("初始化失败", ex);
  8. }
  9. }

init() 方法内部包含很多初始化行为,具体包括:

  1. 构建配置
  2. 初始化模板引擎
  3. 初始化自定义方法,即 beetl.properties 中配置的方法
  4. 初始化拓展资源,包括 formatMapdefaultFormatmap
  5. 初始化 tag,即配置里的 tagFactoryMap
  6. 初始化虚拟函数
  7. 初始化缓冲区

init() 方法

  1. protected void init() {
  2. conf.build();
  3. engine = TemplateEngineFactory.getEngine(conf.getEngine());
  4. this.initFunction();
  5. this.initFormatter();
  6. this.initTag();
  7. this.initVirtual();
  8. this.initBuffers();
  9. classSearch = new ClassSearch(conf.getPkgList(), this);
  10. nativeSecurity = (NativeSecurityManager) ObjectUtil.instance(conf.getNativeSecurity(), this.classLoader);
  11. if (conf.errorHandlerClass == null) {
  12. errorHandler = null;
  13. } else {
  14. errorHandler = (ErrorHandler) ObjectUtil.instance(conf.errorHandlerClass, classLoader);
  15. }
  16. htmlTagAttrNameConvert = (AttributeNameConvert)ObjectUtil.instance(conf.htmlTagAttributeConvert, classLoader);
  17. }

总结

GroupTemplate 是 Beetl 模板的核心类,我们看到这个类非常重,里面包含了大量属性,这些属性都为后续模板计算提供相关资源。类中的大部分属性都使用了 HashMap 来存放上下文信息,这为我们设计一些类时提供了一定参考。其中缓存管理比较简单,基本就是封装了 ConcurrentHashMap 的方法,只对外暴露 4 个方法,这也是我们构建本地缓存管理的常用方式:基于 ConcurrentHashMap 构建暴露特定方法的自定义缓存管理器。

原文链接:https://www.cnblogs.com/rottenorange-cn/p/18153101

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号