Home > Back-end >  Spring thymeleaf TemplateEngine Getting error Template engine has already been initialized when crea
Spring thymeleaf TemplateEngine Getting error Template engine has already been initialized when crea

Time:06-16

When i create a pdf from this html file everything works perfectly the first time and creates the pdf to my local machine. But when i create it again it returns this error "Template engine has already been initialized (probably because it has already been executed or a fully-built Configuration object has been requested from it. At this state, no modifications on its configuration are allowed." If i restart my local application server it works again the first time. I've also tried to clear the cache using templateEngine.clearTemplateCache().

It looks like when i run it the second time its using the cached template resolver.

@Service
public class LetterService {

    @Autowired
    private TemplateEngine templateEngine;

     private String processPdfTemplate(Map<String, Object> variables) {
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateEngine.setTemplateResolver(templateResolver);


        Context context = new Context();
        context.setVariables(variables);
        context.setLocale(Locale.getDefault());

        return templateEngine.process("index", context);
    }
} 

CodePudding user response:

You used TemplateEngine from Spring Bean. It's not thread-safe and can't re-setup the same object twice. Use local varable instead

     private String processPdfTemplate(Map<String, Object> variables) {
        TemplateEngine templateEngine = new SpringTemplateEngine();
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateEngine.setTemplateResolver(templateResolver);


        Context context = new Context();
        context.setVariables(variables);
        context.setLocale(Locale.getDefault());

        return templateEngine.process("index", context);
    }

or if you want to cache the TemplateEngine for the same Filepath, you can cache it with ConcurrentHashMap. There is also an alternative to create your own TemplateEngine Bean with your own TemplateResolver.

  • Related