Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a @Service bean from Thymeleaf under Spring Boot

I have a bean that is defined as a service:

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

It's possible to autowire it in my app and use it:

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

When I try to use it in a Thymeleaf template I receive this error message:

org.springframework.expression.spel.SpelEvaluationException: EL1057E: No bean resolver registered in the context to resolve access to bean 'fileHandling'

This is the relevant part of my template:

<td th:text="${@fileHandling.doSomething()}">...</td>  

This is how I access the templating engine:

final Context ctx = new Context();
ctx.setVariable("files", map);
ctx.setVariable("fileHandling",fh);

String html = templateEngine.process("flattopic", ctx);

I receive the error message no matter if I try to access the bean directly or after setVariable("fileHandling"). The syntax I use complies to what I see in chapter 5 of https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html.

I've seen similar questions which apply to basic SPEL (this one) or an unanswered question specific to Thymeleaf. The alternative to switch from a bean to a static class and use ${T(org.foo.bar.package.FileHandling).doSomething()} is something that I would like to avoid.

How can I solve this or make the bean accessible ?

like image 389
Marged Avatar asked Oct 20 '25 10:10

Marged


1 Answers

"Call a bean from Thymeleaf under Spring Boot" is also "Call a bean from Thymeleaf under Spring MVC". For example:

Interface

package com.example;

public interface UrlService {

    String getApplicationUrl();

}

You has component 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";
    }

}

In Thymeleaf template file foo.html

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

Source: https://www.thymeleaf.org/doc/articles/springmvcaccessdata.html#spring-beans

like image 119
Do Nhu Vy Avatar answered Oct 23 '25 03:10

Do Nhu Vy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!