我有一个spring mvc应用程序,我试图将一个日期LocalDate渲染成一个字符串,对于普通的视图它可以工作,但对于电子邮件它不起作用并抛出以下错误:
引起: org.springframework.core.convert.ConverterNotFoundException:没有 转换器发现能够从类型[java.time.LocalDate]转换 输入[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);
}
}
答案 0 :(得分:7)
我进行了调试,发现如果我们使用新构造的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);
}
}
问题解决了。