2016-07-22 63 views
2

我在那裏我試圖呈現一個日期變成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); 
    } 
} 

回答

3

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

問題解決了。