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 ?
"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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With