Formatter not applied to values (non-mvc SpringBoot application)
fml2 opened this issue · 1 comments
I've asked this question on StackOverflow. Since I think that the behaviour I see is a bug, I'm creating this issue.
I have a SpringBoot based application (SpringBoot 3.2.4). The application is not a web application, i.e. it does not use servlets, views etc.
In the application, I want to create a report in the HTML format and send it via email. For creating the HTML, I want to use ThymeLeaf. I do it like this:
Context context = new Context();
context.setVariable("reportName", reportName);
context.setVariable("someOtherData", data);
return templateEngine.process("report", context);
The templateEngine
bean is prepared and configured by SpringBoot.
Some of the values to be displayed in the report are of type java.time.Duration
, others are of type java.util.Date
(and some others). My goal is that those values are automatically formatted as I like it.
For that purpose, I created Printer classes and registered them in the Spring registry:
@Configuration
public class Config implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addPrinter(new DatePrinter());
registry.addPrinter(new DurationPrinter());
}
}
where e.g. the DatePrinter
looks like
public class DatePrinter implements Printer<Date> {
@Override
public String print(Date date, Locale locale) {
return new SimpleDateFormat("yyyy-MM-dd").format(date);
}
}
But that registrations do not seem to have any effect: In the report, all the values are displayed via their toString
method. The report template looks e.g. like this: <td>[[${process.startTime}]]</td>
, where the field startTime
is a java.util.Date
. My custom formatter does not get applied to it.
I also tried to register the formatters as Formatter
s rather than Printer
s, but it still didn't work.
In my view, I did everything as described e.g. in the Thymeleaf docs.
The question has been answered on StackOverflow: https://stackoverflow.com/questions/78204832/how-to-register-a-formatter-for-a-type-in-thymeleaf-non-web-environment.