Labs ICT
Pro Login

Caching

Template caching and cache strategies.

Enabling Template Caching

By default, Spring Boot enables Thymeleaf template caching. This means once a template is parsed, it stays in memory and doesn't get re-read from disk on every request. It's a big performance win for production.


# application.properties
spring.thymeleaf.cache=true
    

With caching on, the first request parses the template, and subsequent requests use the cached version. You won't notice any difference in output — it's purely a speed optimization.

Disabling Cache in Development

During development, you want changes to templates to show up immediately without restarting the server. Turning off cache lets you edit and refresh without any hassle.


# application-dev.properties
spring.thymeleaf.cache=false
    

You can also use Spring profiles to manage this automatically. Set cache to false in your dev profile and true in production. That way, you never accidentally ship a dev setting to production.

Try it Yourself →

Template Caching Strategies

Thymeleaf uses a template cache that stores parsed template objects. You can configure the cache TTL and max size through Spring's caching infrastructure.


spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
    

For most applications, the default settings work perfectly. If you're serving a huge number of templates, you might want to tune the cache size. But honestly, the defaults handle the vast majority of cases.

Precompiled Templates

Thymeleaf supports precompiled templates, which means your templates are compiled into Java classes at build time. This eliminates runtime parsing overhead entirely.


# pom.xml configuration
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
</dependency>
    

Precompiled templates are especially useful in large projects where startup time matters. The templates get compiled during your normal build process, and the application loads them as regular Java classes.

When to Use What

Here's a simple rule: cache on for production, cache off for development. If you're working on a template, disable caching so you see changes instantly. When you deploy, make sure caching is back on.


# application-prod.properties
spring.thymeleaf.cache=true

# application-local.properties
spring.thymeleaf.cache=false
    

This approach gives you the best of both worlds — fast iteration during development and optimal performance in production.