非Web场景下Spring Boot结合Thymeleaf模板渲染实现方案咨询
在非Web Spring Boot应用中使用Thymeleaf渲染模板
步骤1:引入正确依赖
因为是非Web应用,无需引入spring-boot-starter-web,只需核心Spring Boot依赖和Thymeleaf starter:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
步骤2:配置Thymeleaf模板路径
在application.properties中指定模板来源(文件系统)及相关属性:
# 本地模板文件目录(示例为项目根目录下的templates文件夹) spring.thymeleaf.prefix=file:./templates/ # 模板文件后缀 spring.thymeleaf.suffix=.html # 开发环境关闭缓存,生产环境建议开启 spring.thymeleaf.cache=false # 模板解析模式 spring.thymeleaf.mode=HTML
若模板放在类路径(如
src/main/resources/templates),将prefix改为classpath:/templates/即可。
步骤3:在@Service中实现模板渲染
直接注入Thymeleaf的TemplateEngine,通过Context绑定变量并渲染模板:
import org.springframework.stereotype.Service; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; @Service public class S3FileTemplater { private final TemplateEngine templateEngine; // 构造注入TemplateEngine(Spring会自动配置该Bean) public S3FileTemplater(TemplateEngine templateEngine) { this.templateEngine = templateEngine; } // 渲染模板并返回HTML字符串 public String renderVendorTemplate(User user) { Context context = new Context(); // 绑定User对象到模板上下文,模板中可通过${user.xxx}访问属性 context.setVariable("user", user); // 调用process方法渲染模板,参数为模板文件名(无需带后缀) return templateEngine.process("vendor-abc", context); } // 后续可添加S3上传逻辑,将渲染后的HTML字符串转为文件上传 // public void uploadRenderedHtmlToS3(String renderedHtml, String s3ObjectKey) { // // 调用AWS S3 SDK完成上传 // } }
步骤4:编写Thymeleaf模板
在配置的模板目录下创建vendor-abc.html,示例内容:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Vendor ABC 模板</title> </head> <body> <h1>您好,<span th:text="${user.name}"></span>!</h1> <p>您的邮箱是:<span th:text="${user.email}"></span></p> </body> </html>
关键注意点
- Spring Boot会自动配置
TemplateEngine,无需手动初始化 - 生产环境开启
spring.thymeleaf.cache=true,减少模板重复解析开销 - 若需自定义模板解析逻辑,可通过配置
TemplateResolverBean扩展
内容的提问来源于stack exchange,提问作者hotmeatballsoup
相关产品推荐
相关产品推荐

