我調試,發現,如果我們使用一個新建成的背景下,將創建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);
}
}
問題解決了。