java – Thymeleaf电子邮件模板和ConversionService
发布时间:2020-12-15 04:35:18 所属栏目:Java 来源:网络整理
导读:我有一个 spring mvc应用程序,我试图将一个日期LocalDate渲染成一个字符串,对于普通的视图它可以工作,但对于电子邮件它不起作用并抛出以下错误: Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of c
我有一个
spring mvc应用程序,我试图将一个日期LocalDate渲染成一个字符串,对于普通的视图它可以工作,但对于电子邮件它不起作用并抛出以下错误:
码: import org.thymeleaf.context.Context; import org.thymeleaf.spring4.SpringTemplateEngine; @Service public class EmailService { @Autowired private SpringTemplateEngine templateEngine; public String prepareTemplate() { // ... Context context = new Context(); this.templateEngine.process(template,context); } } 解决方法
我进行了调试,发现如果我们使用新构造的Context,它将创建另一个ConversionService实例,而不是使用DefaultFormattingConversionService bean.
在thymeleaf spring的SpelVariableExpressionEvaulator中,我们看到以下代码 final Map<String,Object> contextVariables = computeExpressionObjects(configuration,processingContext); EvaluationContext baseEvaluationContext = (EvaluationContext) processingContext.getContext().getVariables(). get(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME); if (baseEvaluationContext == null) { // Using a standard one as base: we are losing bean resolution and conversion service!! baseEvaluationContext = new StandardEvaluationContext(); } 要解决此问题,我们必须确保我们的上下文包含使用正确的转换服务初始化的百万美元评估上下文. import org.thymeleaf.context.Context; import org.thymeleaf.spring4.SpringTemplateEngine; import org.springframework.core.convert.ConversionService; import org.springframework.context.ApplicationContext; @Service public class EmailService { @Autowired private SpringTemplateEngine templateEngine; // Inject this @Autowired private ApplicationContext applicationContext; // Inject this @Autowired private ConversionService mvcConversionService; public String prepareTemplate() { // ... Context context = new Context(); // Add the below two lines final ThymeleafEvaluationContext evaluationContext = new ThymeleafEvaluationContext(applicationContext,mvcConversionService); context.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME,evaluationContext); this.templateEngine.process(template,context); } } 问题解决了. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |