Mar*_*ged 4 thymeleaf spring-boot
我有一个被定义为服务的 bean:
@Service
public class FileHandling {
public void doSomething() {
...
Run Code Online (Sandbox Code Playgroud)
可以在我的应用程序中自动装配它并使用它:
@Autowired
@Qualifier("fileHandling")
FileHandling fh;
Run Code Online (Sandbox Code Playgroud)
当我尝试在 Thymeleaf 模板中使用它时,我收到以下错误消息:
org.springframework.expression.spel.SpelEvaluationException:EL1057E:上下文中没有注册任何 bean 解析器来解析对 bean 'fileHandling' 的访问
这是我的模板的相关部分:
<td th:text="${@fileHandling.doSomething()}">...</td>
Run Code Online (Sandbox Code Playgroud)
这是我访问模板引擎的方式:
final Context ctx = new Context();
ctx.setVariable("files", map);
ctx.setVariable("fileHandling",fh);
String html = templateEngine.process("flattopic", ctx);
Run Code Online (Sandbox Code Playgroud)
I receive the error message no matter if I try to access the bean directly or after setVariable("fileHandling")
. The syntax I use complies to what I see in chapter 5 of https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html.
I've seen similar questions which apply to basic SPEL (this one) or an unanswered question specific to Thymeleaf.
The alternative to switch from a bean to a static class and
use ${T(org.foo.bar.package.FileHandling).doSomething()}
is something that I would like to avoid.
How can I solve this or make the bean accessible ?
“在Spring Boot下从Thymeleaf调用bean”也是“在Spring MVC下从Thymeleaf调用bean”。例如:
界面
package com.example;
public interface UrlService {
String getApplicationUrl();
}
Run Code Online (Sandbox Code Playgroud)
你有组件MyConfiguration
package com.example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfiguration {
@Bean(name = "urlService")
public UrlService urlService() {
return () -> "domain.com/myapp";
}
}
Run Code Online (Sandbox Code Playgroud)
在 Thymeleaf 模板文件中foo.html
<div th:text="${@urlService.getApplicationUrl()}">...</div>
Run Code Online (Sandbox Code Playgroud)
资料来源:https ://www.thymeleaf.org/doc/articles/springmvcaccessdata.html#spring-beans
归档时间: |
|
查看次数: |
4495 次 |
最近记录: |