Spring thymeleaf模板引擎找不到模板文件

时间:2020-05-12 04:53:05

标签: spring-boot thymeleaf

我正在尝试使用Spring Boot和百里香叶发送嵌入式电子邮件。我添加了新的模板文件“ test-email.html” enter image description here

我有以下bean配置

@Qualifier("emailSender")
@Autowired
private val templateEngine: SpringTemplateEngine? = null

@Bean(name = ["emailSender"])
fun springTemplateEngine(): SpringTemplateEngine? {
    val templateEngine = SpringTemplateEngine()
    templateEngine.addTemplateResolver(htmlTemplateResolver())
    return templateEngine
}

@Bean
fun htmlTemplateResolver(): SpringResourceTemplateResolver? {
    val emailTemplateResolver = SpringResourceTemplateResolver()
    emailTemplateResolver.prefix = "/templates/email/"
    emailTemplateResolver.suffix = ".html"
    emailTemplateResolver.templateMode = TemplateMode.HTML
    emailTemplateResolver.characterEncoding = StandardCharsets.UTF_8.name()
    return emailTemplateResolver
}

以下功能用于发送解析模板和发送电子邮件。

fun sendTemplateMessage(to: String, subject: String, text: String) {
    val mimeMessage: MimeMessage? = emailSender?.createMimeMessage()
    val helper = mimeMessage?.let { MimeMessageHelper(it, "utf-8") }

    val context = Context()
    context.setVariable("msg", "This is test message")


    val htmlMsg = templateEngine!!.process("test-email", context)
    helper?.setText(htmlMsg, true)

    helper?.setTo(to)
    helper?.setSubject(subject)
    emailSender?.send(mimeMessage)
}

但是这给出了FileNotFound异常。

原因:java.io.FileNotFoundException:ReactiveWebContext资源[/templates/email/test-email.html]无法打开,因为它不存在

我如何提供模板引擎的模板文件路径?

1 个答案:

答案 0 :(得分:1)

添加classpath:作为文件路径的前缀。背后的原因是它将从部署jar的位置获取相对路径,否则会将给定路径视为绝对路径。

因此,如下更改代码:

@Bean
fun htmlTemplateResolver(): SpringResourceTemplateResolver? {
    val emailTemplateResolver = SpringResourceTemplateResolver()
    emailTemplateResolver.prefix = "classpath:/templates/email/"
    emailTemplateResolver.suffix = ".html"
    emailTemplateResolver.templateMode = TemplateMode.HTML
    emailTemplateResolver.characterEncoding = StandardCharsets.UTF_8.name()
    return emailTemplateResolver
}