Thymeleaf调用Spring的Bean的函数

问题见:https://stackoverflow.com/questions/53803497

为什么按照官网上的写法调用@Bean报错:EL1057E: No bean resolver registered in the context to resolve access to bean

有时候我们希望自己去通过thymeleaf进行解析文本,调用自定义的函数。比如

Context context = new Context();
context.setVariables(dataMap);
templateEngine.process(templateName, context);

如果我们在模板里使用了 ${@beanName.method()},此时会报错:

EL1057E: No bean resolver registered in the context to resolve access to bean

但是如果我们是通过模板进行MVC页面渲染就不会报错,其实原因就是因为此时的context里缺少了spring的Beans的信息,通过spring mvc渲染时,框架会加入这些信息。那么手动渲染时我们也添加Beans的信息就可以了。

Context context = new Context();
context.setVariables(dataMap);

ThymeleafEvaluationContext tec = new ThymeleafEvaluationContext(applicationContext, null);
dataMap.put(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME, tec);
templateEngine.process(templateName, context);

此时在进行渲染就正常了。

如果想更接近 Spring MVC 解析逻辑的,参考如代码:

@RequestMapping(value = "/uploadApk", produces = "text/javascript")
@ResponseBody
public String fragUploadApk(@NonNull final HttpServletRequest request, @NonNull final HttpServletResponse response) {        
    final WebContext context = new WebContext(request, response, request.getServletContext(), request.getLocale());

    # 此处使用 Spring MVC 默认的 FormattingConversionService.class 完成对数据的格式化(Springboot 2.7.11)
    final FormattingConversionService conversionService = applicationContext.getBean(FormattingConversionService.class);
    final ThymeleafEvaluationContext thymeleafEvaluationContext = new ThymeleafEvaluationContext(requireApplicationContext(), conversionService);
    context.setVariable(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME, thymeleafEvaluationContext);
    templateEngine.process(templateName, context);
}

参考链接