从 Thymeleaf Spring 视图尝试调用方法时出错 [英] Error trying call method from view Thymeleaf Spring
问题描述
当我尝试从视图调用方法时遇到问题.
I have a problem when im try to call a method from view.
我的 Java 类和方法
My Java class with methods
public class FuncionesMuestroteca {
@Bean
public static boolean estoyMuestroteca() {
boolean resultado = false;
return resultado;
}
}
现在我从 header.html 调用函数
Now i call function from header.html
<th:block th:text="${FuncionesMuestroteca.estoyMuestroteca()}"/>
在 POM.xml 中,我导入了 thymeleaf-extras 版本 2.1.0.RELEASE 和 thymeleaf 2.1.5
In POM.xml i have imported thymeleaf-extras version 2.1.0.RELEASE and thymeleaf 2.1.5
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
<version>2.1.0.RELEASE</version>
这里是 StackTrace
And here the StackTrace
org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method estoyMuestroteca() on null context object
如果您需要其他任何东西,请随时告诉我,我会提供的.提前致谢.
If you need anything else, do not hesitate to tell me and I'll put it. Thank you in advance.
新的堆栈跟踪:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'estoyMuestroteca' available
HTML 编辑
<div th:text="${@estoyMuestroteca.estoyMuestroteca()}"></div>
方法实际
@Configuration
public class FuncionesMuestroteca {
@Bean(name = "estoyMuestroteca")
public boolean estoyMuestroteca() {
boolean resultado = false;
return resultado;
}
}
推荐答案
这里有几件事.一、静态方法:
A couple things here. First, the static method:
public class FuncionesMuestrotecaUtilidad { //note name change
public static boolean estoyMuestroteca() {
return false; //don't need to create extra variables if this is what you need
}
}
在您的 HTML 中,您可以使用正确的语法来调用静态方法:
In your HTML, you can use the proper syntax for calling a static method:
<th:block th:text="${T(com.package.FuncionesMuestrotecaUtilidad).estoyMuestroteca()}">
<!-- do whatever -->
</th:block>
将 com.package
替换为您的包名称.此外,这不需要 @Bean
或 @Configuration
注释 - 您只是直接调用静态方法.
Replace com.package
with your package name. Also, this does not need the @Bean
or @Configuration
annotation - you are just calling a static method directly.
对这一切的主要警告是,可能有更好的方法来设计代码而不使用静态方法.但这超出了本问题的范围.
The major caveat to all this is that there might be a better way to design the code without using static methods. But that is outside the scope of this question.
最后,迁移到更新版本的 Thymeleaf 很有意义.它速度更快,限制更少,功能更多.
Lastly, it makes a lot of sense to move to a newer version of Thymeleaf. It's far faster, less restrictive, and has more features.
这篇关于从 Thymeleaf Spring 视图尝试调用方法时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!