Rej*_*eri 3 java spring spring-mvc thymeleaf spring-boot
我有一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
我进行了调试,发现如果我们使用新构造的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();
}
Run Code Online (Sandbox Code Playgroud)
要解决此问题,我们必须确保我们的上下文包含使用正确的转换服务初始化的百万美元评估上下文.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
问题解决了.
| 归档时间: |
|
| 查看次数: |
476 次 |
| 最近记录: |