Search code examples
javaspringspring-mvcspring-bootthymeleaf

Error trying call method from view Thymeleaf Spring


I have a problem when im try to call a method from view.

My Java class with methods

public class FuncionesMuestroteca {
    @Bean
    public static boolean estoyMuestroteca() {
        boolean resultado = false;

        return resultado;
    }
}

Now i call function from header.html

<th:block th:text="${FuncionesMuestroteca.estoyMuestroteca()}"/>

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>

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.

new StackTrace:

 org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'estoyMuestroteca' available

HTML Edit

<div th:text="${@estoyMuestroteca.estoyMuestroteca()}"></div>

Method actual

@Configuration
public class FuncionesMuestroteca {
    @Bean(name = "estoyMuestroteca")
    public boolean estoyMuestroteca() {
        boolean resultado = false;

        return resultado;
    }
}

I add an image of the folder structure of the project


Solution

  • 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
        }
    }
    

    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>
    

    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.

    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.