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的信息就可以了。

1 Context context = new Context();
2 context.setVariables(dataMap);
3 
4 ThymeleafEvaluationContext tec = new ThymeleafEvaluationContext(applicationContext, null);
5 dataMap.put(ThymeleafEvaluationContext.THYMELEAF_EVALUATION_CONTEXT_CONTEXT_VARIABLE_NAME, tec);
6 templateEngine.process(templateName, context);

此时在进行渲染就正常了

posted @ 2022-04-05 22:45  国家重点扶贫攻坚对象  阅读(395)  评论(0编辑  收藏  举报