V.V*_*ejo 0 java spring spring-mvc thymeleaf spring-boot
当我尝试从视图调用方法时遇到问题。
我的 Java 类与方法
public class FuncionesMuestroteca {
@Bean
public static boolean estoyMuestroteca() {
boolean resultado = false;
return resultado;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我从 header.html 调用函数
<th:block th:text="${FuncionesMuestroteca.estoyMuestroteca()}"/>
Run Code Online (Sandbox Code Playgroud)
在 POM.xml 中,我导入了 thymeleaf-extras 版本 2.1.0.RELEASE 和 thymeleaf 2.1.5
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
<version>2.1.0.RELEASE</version>
Run Code Online (Sandbox Code Playgroud)
这里是 StackTrace
org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method estoyMuestroteca() on null context object
Run Code Online (Sandbox Code Playgroud)
如果您需要其他任何东西,请不要犹豫,告诉我,我会放的。先感谢您。
新的堆栈跟踪:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'estoyMuestroteca' available
Run Code Online (Sandbox Code Playgroud)
HTML 编辑
<div th:text="${@estoyMuestroteca.estoyMuestroteca()}"></div>
Run Code Online (Sandbox Code Playgroud)
方法实际
@Configuration
public class FuncionesMuestroteca {
@Bean(name = "estoyMuestroteca")
public boolean estoyMuestroteca() {
boolean resultado = false;
return resultado;
}
}
Run Code Online (Sandbox Code Playgroud)
vph*_*nyc 10
这里有几件事。一、静态方法:
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
}
}
Run Code Online (Sandbox Code Playgroud)
在您的 HTML 中,您可以使用正确的语法来调用静态方法:
<th:block th:text="${T(com.package.FuncionesMuestrotecaUtilidad).estoyMuestroteca()}">
<!-- do whatever -->
</th:block>
Run Code Online (Sandbox Code Playgroud)
替换com.package为您的包名。此外,这不需要@Beanor@Configuration注释 - 您只是直接调用静态方法。
所有这一切的主要警告是,可能有更好的方法来设计代码而不使用静态方法。但这超出了这个问题的范围。
最后,迁移到更新版本的 Thymeleaf 很有意义。它速度更快,限制更少,并且具有更多功能。
| 归档时间: |
|
| 查看次数: |
8106 次 |
| 最近记录: |