Skip to content

2.5.1 Caching templates

By default, templates are parsed only once—when they’re first used—and the results of that parse are cached for subsequent use. This is a great feature for production, because it prevents redundant template parsing on each request and thus improves performance.

That feature is not so awesome at development time, however. Let’s say you fire up your application, hit the taco design page, and decide to make a few changes to it. When you refresh your web browser, you’ll still be shown the original version. The only way you can see your changes is to restart the application, which is quite inconvenient.

Fortunately, we have a way to disable caching. All we need to do is set a templateappropriate caching property to false. Table 2.3 lists the caching properties for each of the supported template libraries.

Table 2.3 Properties to enable/disable template caching

TemplateCache-enable property
Freemarkerspring.freemarker.cache
Groovy Templatesspring.groovy.template.cache
Mustachespring.mustache.cache
Thymeleafspring.thymeleaf.cache

By default, all of these properties are set to true to enable caching. You can disable caching for your chosen template engine by setting its cache property to false. For example, to disable Thymeleaf caching, add the following line in application.properties:

text
spring.thymeleaf.cache = false

The only catch is that you’ll want to be sure to remove this line (or set it to true) before you deploy your application to production. One option is to set the property in a profile. (We’ll talk about profiles in chapter 6.)

A much simpler option is to use Spring Boot’s DevTools, as we opted to do in chapter 1. Among the many helpful bits of development-time help offered by DevTools, it will disable caching for all template libraries but will disable itself (and thus reenable template caching) when your application is deployed.

Released under the MIT License.