gpt4 book ai didi

java - Thymeleaf 电子邮件模板和 ConversionService

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:22:47 43 4
gpt4 key购买 nike

我有一个 spring mvc 应用程序,我试图在其中将日期 LocalDate 呈现为字符串,对于普通 View 它可以工作但对于电子邮件它不起作用并抛出以下错误:

Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.time.LocalDate] to type [java.lang.String]

代码:

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);
}
}

最佳答案

我调试了,发现如果我们使用新构造的上下文,它将创建另一个 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();
}

要解决这个问题,我们必须确保我们的上下文包含使用正确的转换服务初始化的 thymeleaf 评估上下文。

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);
}
}

问题已解决。

关于java - Thymeleaf 电子邮件模板和 ConversionService,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38518377/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com