Thymeleaf电子邮件模板和ConversionService
问题描述:
我在那里我试图呈现一个日期变成LOCALDATE一个字符串,它工作正常的观点,但对于邮件它不工作,并抛出了以下错误的Spring MVC应用程序:Thymeleaf电子邮件模板和ConversionService
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豆。
在thymeleaf春天的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);
}
}
问题解决了。