Java – thymeleaf email template and conversionservice
•
Java
I have a spring MVC application. I try to render a date localdate as a string. It works for normal views, but it doesn't work for e-mail and throws the following error:
Code:
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); } }
Solution
I debugged and found that if we use the newly constructed context, it will create another conversionservice instance instead of using the defaultformattingconversionservice bean
In the spelvariableexpressionevaluator of thymeleaf spring, we see the following code
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(); }
To solve this problem, we must ensure that our context contains a million dollar evaluation context initialized with the correct transformation service
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); } }
The problem is solved
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码