【问题标题】:How can I check in Thymeleaf if a spring bean exists如果存在春豆,我如何检查 Thymeleaf
【发布时间】:2019-11-06 01:58:38
【问题描述】:

我正在编写一个 Thymeleaf 模板,该模板将从 Spring bean 中获取一些数据。我的项目正在使用 spring-boot(如果重要的话)。在某些情况下,某个 bean 不可用。如何检查模板内部是否存在 bean?

我试着检查一个变量,但它不起作用

<div th:if="${@myBean != null}" th:text="Bean exists"></div>

我得到一个

NoSuchBeanDefinitionException:没有名为“myBean”的 bean 可用

【问题讨论】:

  • 你可以为你的模型设置一个指标
  • 我已经搜索过了,我似乎找不到这样做的方法...

标签: spring-boot thymeleaf


【解决方案1】:

使用

${#objects.nullSafe(obj,default)}

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#objects

更简单的是,您可以检查 bean 是否存在于 Spring 的 Controller 中。

【讨论】:

  • 正如我所担心的,同样的异常被抛出,因为nullSafe() 方法可能只是一个空比较,就像我所做的一样(见问题)。对于文档porpouses,我想出的是${#objects.nullSafe(@myBean, @existingBean).someMethod()}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 2017-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多