@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
任何想法?
使用Context代替WebContext
import org.thymeleaf.context.Context;
WebContext的生命周期取决于请求线程(主线程)。
一旦主线程返回响应,它将销毁WebContext。
String content=templateEngine.process(template, context);
上面的代码将尝试访问已被销毁的对象,因此它将抛出异常
试一试;)
听起来你的Async没有启用,看看这个教程,最好的方法是打开它。
http://blog.adaofeliz.com/2014/11/02/spring-mvc-without-xml-configuration/总之,在启动时,您需要确保DispatcherServlet注册了以下选项:servlet.setAsyncSupported(true);
根据评论讨论,请找到一个类似的围绕Async不工作属性和用户不得不强制注册的问题:
Spring @Async Not Working