要在spring boot 2.0中实现groovy模板动态渲染,需手动集成groovy原生simpletemplateengine,排除spring-boot-starter-groovy-templates,引入groovy 2.5.14依赖,模板以.groovy为后缀且首行为

要在Spring Boot 2.0项目中实现Groovy模板的动态渲染,必须避开Spring Boot 2.1+才默认支持的spring-boot-starter-groovy-templates,改用底层Groovy原生模板引擎手动集成,否则启动会因类缺失直接失败。
引入兼容的Groovy依赖
打开pom.xml,删除任何groovy-templates starter,仅保留核心Groovy运行时:
注意:Spring Boot 2.0.x基线对应Groovy 2.5.x,【使用2.4.x或3.x会导致SimpleTemplateEngine初始化失败】。Maven会自动拉取groovy-xml、groovy-json等子模块,无需额外声明。
编写可热加载的Groovy模板文件
在src/main/resources/templates/下新建email.groovy:
def title = request.title ?: '系统通知'
def content = request.content ?: '无内容'
%>
${title}
${content}
模板必须以.groovy为后缀,且首行必须是——这是<code>SimpleTemplateEngine识别脚本块的硬性要求,写成或<code>不换行都会解析失败。
构建动态渲染服务
创建TemplateRenderer工具类:
第一步:声明静态缓存与引擎实例
private static final ConcurrentHashMap
private static final SimpleTemplateEngine ENGINE = new SimpleTemplateEngine();
第二步:定义渲染方法,传入模板路径和数据上下文
public String render(String templatePath, Map
Template template = CACHE.computeIfAbsent(templatePath, k -> {
InputStream is = getClass().getClassLoader().getResourceAsStream(k);
return ENGINE.createTemplate(is);
});
return template.make(context).toString();
}
第三步:调用示例
Map
data.put("title", "订单已支付");
data.put("content", "您的订单#202608061234已成功支付。");
String html = renderer.render("templates/email.groovy", data);











