spring-boot - 如何在 Spring Boot 下从 Thymeleaf 调用 @Service bean

标签 spring-boot thymeleaf

我有一个定义为服务的 bean:

@Service
public class FileHandling {
  public void doSomething() {
...

可以在我的应用程序中 Autowiring 并使用它:
@Autowired
@Qualifier("fileHandling")
FileHandling fh;

当我尝试在 Thymeleaf 模板中使用它时,我收到以下错误消息:

org.springframework.expression.spel.SpelEvaluationException: EL1057E: No bean resolver registered in the context to resolve access to bean 'fileHandling'



这是我模板的相关部分:
<td th:text="${@fileHandling.doSomething()}">...</td>  

这是我访问模板引擎的方式:
final Context ctx = new Context();
ctx.setVariable("files", map);
ctx.setVariable("fileHandling",fh);

String html = templateEngine.process("flattopic", ctx);

无论我尝试直接访问 bean 还是在 setVariable("fileHandling") 之后,我都会收到错误消息.我使用的语法符合我在 https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html 的第 5 章中看到的内容.

我见过类似的问题适用于基本 SPEL(这个 one)或一个 unanswered特定于 Thymeleaf 的问题。
从 bean 切换到静态类的替代方法
使用 ${T(org.foo.bar.package.FileHandling).doSomething()}是我想避免的事情。

我该如何解决这个问题或使 bean 可访问?

最佳答案

“在 Spring Boot 下从 Thymeleaf 调用一个 bean”也是“在 Spring MVC 下从 Thymeleaf 调用一个 bean”。例如:

界面

package com.example;

public interface UrlService {

    String getApplicationUrl();

}

您有组件 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";
    }

}

在 Thymeleaf 模板文件中 foo.html
<div th:text="${@urlService.getApplicationUrl()}">...</div>

来源:https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html#spring-beans

关于spring-boot - 如何在 Spring Boot 下从 Thymeleaf 调用 @Service bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53803497/

相关文章:

java - 运行应用程序时tomcat未启动

java - 获取环境变量并通过 SonarLint 的正确方法

spring - Spring MVC 中的 HandlerInterceptor.afterCompletion() 更改响应代码

java - 使用 Thymeleaf 和 Spring 动态链接到图像

java - 如何获取 Thymeleaf 模板中环境变量的值?

java - Spring Integration 测试加载注解 Bean

mysql - 在idea中调试启动Spring boot应用程序时,Liquibase再次运行变更集

datatables - 蒲公英数据表 + Thymeleaf + 分页问题

spring - Thymeleaf:动态构建变量名

java - Thymeleaf 无法识别 Lombok getter 和 setter