How Can We Read And Cache Resources from External Path?

Hasan Kadir Demircan
2 min readMar 11, 2022

You must have used Mustache to read email templates or some resources.
But mustache can read and cache the files in the jar.

Let’s assume that these files (email templates, messages resources) need to be changed when are in the jar, but we don’t want to build&deploy our microservice.

So, We can carry on these to the external path&config to avoid building and deploying our services.

If we want to read them from an external path and want it to automatically cache it after the first read, what should we do?
When I started to research this situation, I found the trimou library which covers my demands.

What is the Trimou Library?

Trimou is yet another Mustache implementation written in Java. It’s goal is to provide a simple to use and easy to extend templating engine for any Java SE or Java EE application. So far there are three ready-to-use extensions which provide integration with CDI, Servlets and PrettyTime (see Extensions section for more info).

What are the features?

  • Template caching
  • Extended processing of lambdas
  • Template inheritance
  • Very basic i18n support
  • Extension points (template locators, resolvers, text support, …)

Add Trimou Dependency

To use trimou library we need to add this dependency into pom.xml

<dependency>
<groupId>org.trimou</groupId>
<artifactId>trimou-core</artifactId>
<version>2.5.1.Final</version>
</dependency>

How Can We Use the dependency?

  • resources.email.path we should define the external path in application.yaml.
  • We can build mustacheEngineBuilder in SendMailService as a constructor.
this.engine = MustacheEngineBuilder
.newBuilder()
.addTemplateLocator(new FileSystemTemplateLocator(1, emailPath))
.build();
  • to get an instance from Mustache and create an email template path.
engine.getMustache(createMailPath(emailRequest));
  • createMailPath only creates an extension path(register.html, login.html, welcome.html, etc.)
  • Then, If we want to fill the fields in the mail template like firstName, we can use Mapping.
  • After rendering the email templates, you can send the email.I printed the result on the console instead of sending the email

SendEmailService.java

welcome.html

Postman Simple Request:

{
"from": "kadir",
"emailName" : "welcome.html"
}

Github : Trimou example
more information about trimou.

--

--