Search code examples
javaspringthymeleafspring-annotations

How to read blob format file in thymleaf context


I want to store thymleaf template into database instead of file system.

Because of If I store into file system, This will be major issue if we need to run several nodes of application to distribute the load across servers. Templates should not be big so it will be easy to store them in DB.

Till now I read file through pre-defined path from context, using code like

FileTemplateResolver resolver = new FileTemplateResolver();
String filePath = env.getProperty("external.notification.template.dir");
resolver.setPrefix(filePath);
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setOrder(templateEngine.getTemplateResolvers().size());
resolver.setCacheable(false);
templateEngine.addTemplateResolver(resolver);

It can be possible to create temporary file using blob and read from same location. But There may be good approach available.

Anybody know configuration for to read blob data.

Is there anyway to read blob format file using thymleaf context?


Solution

  • I have created DbTemplateResolver class which extends TemplateResolver. It has inner class, that have a db call which fetch image data from the tabel.

    private class DbResourceResolver implements IResourceResolver {
    
            @Override
            public InputStream getResourceAsStream(TemplateProcessingParameters params, String resourceName) {
    
                NotificationTemplate template = templateService.getNotificationTemplateByName(resourceName);
                if (template != null) {
                    return new ByteArrayInputStream(template.getFileData());
                }
                return null;
            }
    
            @Override
            public String getName() {
                return "dbResourceResolver";
            }
        }
    

    This will be call on process method call.

    mergedMessage = templateEngine.process(fileName, ctx);