【问题标题】:@Async not working with Thymeleaf template engine@Async 不适用于 Thymeleaf 模板引擎
【发布时间】:2015-12-12 16:44:12
【问题描述】:
    @Async
    public void sendEmail(String to, String subject, WebContext context,String template) throws MessagingException
    {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false, "utf-8");
        helper.setTo(to);
        helper.setFrom("some.email@mail-server.com");
        helper.setSubject(subject);
        System.out.println("content1");  //able to see this in console
        String content=templateEngine.process(template, context); //problem with this
        System.out.println("content2");  // not able to see this in console
        helper.setText(content, true);
        mailSender.send(mimeMessage);
    }

我无法发送带有@Async 注释的电子邮件。当我删除此注释时,电子邮件有效。 @Async 没有使用 Thymeleaf 模板引擎。我将@EnableAsync 放在RootConfig 上,我正在创建bean

有什么想法吗?

【问题讨论】:

  • 您是否在应用程序服务器中正确配置了异步,并且您的 web.xml 配置为使用异步?此外,在您的主要帖子中,您有您的电子邮件,请将其删除以避免该帐户上的垃圾邮件。

标签: spring spring-mvc spring-security thymeleaf


【解决方案1】:

使用 Context 代替 WebContext

import org.thymeleaf.context.Context;

WebContext 生命周期取决于请求线程(主线程)。

一旦主线程返回响应,它将销毁 WebContext。

String content=templateEngine.process(template, context);

上面的代码会尝试访问已经被销毁的对象,因此会抛出异常

试一试;)

【讨论】:

  • 我有相同的代码。我有一种使用 IText 生成 PDF 并使用 @Async 的方法。要设置动态数据,我还使用了 org.thymeleaf.TemplateEngine 和 org.thymeleaf.context.WebContext。我有一个用于 html 页面的 css 文件。如果我不使用 WebContext 类,那么 "org.thymeleaf.exceptions.TemplateProcessingException: Link base "/css/styles.css" 不能是上下文相关的 (/...),除非用于执行引擎的上下文实现了 org。 thymeleaf.context.IWebContext)”错误。我的问题是如何在 Async 方法中使用 WebContext?
【解决方案2】:

听起来您的 Async 未启用,请查看本教程以了解打开它的最佳方式。

http://blog.adaofeliz.com/2014/11/02/spring-mvc-without-xml-configuration/

总而言之,在启动时,您需要确保为 DispatcherServlet 注册了以下选项:

servlet.setAsyncSupported(true);

根据评论讨论,请找到关于异步无法正常工作和用户必须强制注册的类似问题:

Spring @Async Not Working

【讨论】:

  • 不幸的是,EnableAsync 实际上并不总是有效。框架中的异步存在一个常见问题,您实际上必须通过 dispatcherservlet 强制注册异步。我在他们探索这个问题的地方添加了一个类似的 stackoverflow 问题。我可以 99.9% 保证这是您的问题(尝试解决上述问题)。
猜你喜欢
  • 2020-08-27
  • 2019-04-11
  • 1970-01-01
  • 1970-01-01
  • 2012-11-09
  • 1970-01-01
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
相关资源
最近更新 更多