【问题标题】:How to call a @Service bean from Thymeleaf under Spring Boot如何在 Spring Boot 下从 Thymeleaf 调用 @Service bean
【发布时间】:2019-05-17 03:04:03
【问题描述】:

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

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

可以在我的应用中自动装配并使用它:

@Autowired
@Qualifier("fileHandling")
FileHandling fh;

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

org.springframework.expression.spel.SpelEvaluationException: EL1057E: 上下文中没有注册 bean 解析器来解析对 bean 的访问 '文件处理'

这是我模板的相关部分:

<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") 之后访问 bean,我都会收到错误消息。我使用的语法符合我在https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html 的第 5 章中看到的内容。

我看到了适用于基本 SPEL(one)或 Thymeleaf 特有的unanswered 问题的类似问题。 从 bean 切换到静态类的替代方法和 我想避免使用${T(org.foo.bar.package.FileHandling).doSomething()}

我怎样才能解决这个问题或使 bean 可访问?

【问题讨论】:

  • @bphilipnyc 感谢您的链接,但我认为我的问题有所不同(请参阅我的编辑)
  • @Marged 不同之处在于您没有在应用程序上下文中定义服务
  • @cralfaro 你的意思是我用 Service 定义的 bean 并且我可以成功地连接到其他任何地方对 Thymeleafs 上下文不可见?我将如何实现这一目标?
  • @Marged 确切地说,您需要在 Configuration 类中定义服务,然后在启动时将服务加载到您的应用程序上下文中,您可以从 thymeleaf 或其他任何地方使用它

标签: spring-boot thymeleaf


【解决方案1】:

"Call a bean from Thymeleaf under Spring Boot"也是"Call a bean from Thymeleaf under Spring MVC"。例如:

界面

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

【讨论】:

  • 谢谢,但我看不出我的代码有什么不同/我必须进行哪些更改
  • @Marged,如果你认为这个答案有帮助,请点击upvote按钮:)
  • 我做了同样的事情,但它不起作用 EL1057E:没有在上下文中注册 bean 解析器来解析对 bean 的访问
猜你喜欢
  • 2019-07-22
  • 2018-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-29
  • 2018-02-04
  • 1970-01-01
  • 2017-05-10
相关资源
最近更新 更多