使用thymeleaf模板发送邮件

原创
2019/12/22 19:30
阅读数 1.2K

Can't call a @Service bean from Thymeleaf under Spring Boot

参考链接https://stackoverflow.com/questions/53803497/how-to-call-a-service-bean-from-thymeleaf-under-spring-boot

今天在使用thymeleaf模板引擎发送邮件时,想在thymeleaf模板中直接调用service的方法,但是一直提示找不到bean。

EL1057E:(pos 1): No bean resolver registered in the context to resolve access to bean

我很好奇,试了好几种创建bean的方法,都不能成功。

找了很久原因,参考官方文档 https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html

官方文档说的也很明确,应该不至于忽悠人。

Thymeleaf allows accessing beans registered at the Spring Application Context with the @beanName syntax,

官网文档列举了示例,按照示例也始终不能成功。

迫于无奈,只能上stackoverflow求助了。找了很久,有一个同样遇到此问题的人,非常执着,在thymeleaf的github下提了issue,也无人回复。 https://github.com/thymeleaf/thymeleaf-spring/issues/201

我一度怀疑此功能了,到了吃饭的点了,就去吃了饭,回来继续研究stackoverflow的回答,大海捞针了。

功夫不负苦心人。

https://stackoverflow.com/questions/31244600/accessing-application-context-beans-from-thymeleaf-email-template

有一个认可度比较高的评论,仔细看了一下,

Found, you need to add a bean resolver in your SpringWebContext. Bean Resolver is created by ThymeleafEvaluationContext.

并贴出了代码:

    Map<String, Object> mergedModel = new HashMap<>();
    ConversionService conversionService = (ConversionService) this.request
            .getAttribute(ConversionService.class.getName()); // might be null!
    ThymeleafEvaluationContext evaluationContext = new ThymeleafEvaluationContext(this.ac,
            conversionService);
    mergedModel.put(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME,
            evaluationContext);
    SpringWebContext ctx = new SpringWebContext(this.request, this.response,
            this.request.getServletContext(), this.request.getLocale(), mergedModel, this.ac);

受此启发,改造我的方法。

核心代码在👇👇👇

org.thymeleaf.context.Context ctx = new org.thymeleaf.context.Context();
ctx.setVariable("type", type);// 向模板传参数
....
ctx.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME, new ThymeleafEvaluationContext(applicationContext,null));

TemplateEngine templateEngine = SpringContextUtil.getBean(TemplateEngine.class);
String html = templateEngine.process("/email",ctx);
System.out.println(html);

再次执行,成功!

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部