spring - 从 thymeleaf 电子邮件模板访问应用程序上下文 bean

标签 spring thymeleaf

我已按照 Thymeleaf 教程“Rich HTML email in Spring with Thymeleaf”使用 Thymeleaf 模板生成电子邮件。 一切都很好,但我无法访问我在应用程序其他地方使用的 ApplicationContext bean。

更具体地说,在我的电子邮件模板中,我希望有类似的内容:

<span th:text="${@myBean.doSomething()}">

其中“myBean”是一个@Component。 这可能吗? 我并不是在寻找类似的解决方法

<span th:text="${myBean.doSomething()}">

bean 作为变量添加到模板处理上下文中。

配置:

@Configuration
@EnableWebMvc
@EnableSpringDataWebSupport
public class MyWebConfig extends WebMvcConfigurerAdapter {
[....]
public ClassLoaderTemplateResolver emailTemplateResolver() {
    ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
    resolver.setPrefix("emailtemplates/");
    resolver.setSuffix(".html");
    resolver.setCharacterEncoding("UTF-8");
    resolver.setTemplateMode("HTML5");
    return resolver;
}

@Bean
public SpringTemplateEngine emailTemplateEngine() {
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.addTemplateResolver(emailTemplateResolver());
    engine.addDialect(new LayoutDialect()); // thymeleaf-layout-dialect
    addSpringSecurityDialect(engine); // thymeleaf-SpringSecurity-dialect
    return engine;
}
[....]
}

电子邮件服务:

@Service
public class MyEmailService {
@Resource SpringTemplateEngine emailTemplateEngine;
[....]
public boolean sendHtmlEmail(...) {
    final Context ctx = new Context(locale);
    ctx.setVariable("someVariable", "someValue"); // Don't want to add myBean here
    final String body = this.emailTemplateEngine.process("myTemplate", ctx);
    [....]

组件:

@Component
public class MyBean {
    public String doSomething() {
        return "Something done!";
    }
}

模板:

<span th:text="${@myBean.doSomething()}">

错误:

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

我正在使用 thymeleaf-2.1.4 和 spring-4.1.6

编辑:

请注意,我无法使用 HttpServletRequest,因为我使用 @Async 方法发送大部分电子邮件,而该方法无法可靠地使用该请求。这就是为什么我使用 Context 而不是 WebContext 的原因(尽管我不知道 SpringWebContext - 我猜如果有人通过“beans”变量创建该类来访问 beans,那么使用 @myBean 表示法一定是不可能的)。

最佳答案

这很令人困惑,因为我们这里有三个不同的上下文:

  • 如果我们以预定方法发送邮件,则为 Spring ApplicationContext,它不是 WebApplicationContext
  • 您在其上设置/添加变量的 Thymeleaf org.thymeleaf.context.Context
  • SpEL 求值上下文org.springframework.expression.EvaluationContext,用于求值 SpEL 表达式。对于 Thymeleaf 来说,这是 ThymeleafEvaluationContext

如果您没有 Spring Web 上下文,您只需添加 ThymeleafEvaluationContext 以及对应用程序上下文的引用作为 Thymeleaf Context 的变量:

例如( Kotlin 语言)

@Service
class TemplateService(
        private val templateEngine: TemplateEngine,
        private val applicationContext: ApplicationContext
) {

    fun processTemplate(locale: Locale, template: String, vararg variables: Pair<String, Any?>): String {
        val context = Context(locale)

        // Set the Thymeleaf evaluation context to allow access to Spring beans with @beanName in SpEL expressions
        context.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME,
                ThymeleafEvaluationContext(applicationContext, null))

        // Set additional variables
        variables.forEach { (key, value) -> context.setVariable(key, value) }

        return templateEngine.process(template, context)
    }
}

关于spring - 从 thymeleaf 电子邮件模板访问应用程序上下文 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31244600/

相关文章:

java - 使用 okta 身份验证通过自定义 userDetailsS​​ervice 在 spring 中添加角色

java - Spring WebFlux : set max file(s) size for uploading files

java - Hibernate persist 方法在方法执行下一步后抛出异常

java - Spring - Thymeleaf 迭代

jquery 和 bootstrap 错误

java - 如何在 spring mvc 应用程序中向数据库添加重复用户名时处理异常

java - Springboot tomcat嵌入NoSuchMethodError : javax. servlet.ServletContext.addFilter

java - Spring boot Thymeleaf 上下文参数未传递给模板

spring-boot - Thymeleaf - 检查模板是否存在

java - 如何在 Thymeleaf 中执行 if-else?