Thymeleaf Configuration with Spring Boot

The home page of my Spring-Data MVC app on GitHub is now seasoned with Thymeleaf and a hint of Bootstrap 3. Here are the highlights of configuring Thymeleaf in a Spring Boot application. Hopefully it will free someone of the dreaded “Cannot find template location: class path resource [templates/] (please add some templates or check your Thymeleaf configuration).”

Version 0.1.3 of my Spring-Data MVC app focuses on configuring Thymeleaf, so branch v0.1.3 is the one you want if you need a streamlined example of Thymeleaf in Spring-Boot.

Thymeleaf is actually pretty tightly integrated with Spring Boot. Here's the ThymeleafAutoConfiguration.java class on GitHub, part of the spring-boot project. If you want to know where that darn “Cannot find template location” error is generated, here it is!

Web Module Taking Shape

Here's the current layout of the Spring-Data app's MVC module with its controllers and webapp. Pretty stark, but perfect if all you want to do is configure Thymeleaf. If you recall, the MVC module works in tandem with the JPA module to form a single Spring Application.

Configuring the Thymeleaf Servlet and Templating Beans

The Thymeleaf beans are configured in the WebConfig Spring configuration class, or whatever class that extends from WebMvcConfigurerAdapter. The classes methods are below.

We'll go into the details in a second, but as an overview, addResourceHandlers provides our static path for CSS, JS, Images and so forth, propertySourcesPlaceholder reads the MessageSource file location from application.properties. ConfigureMessageConverters can be ignored as it primarily pertains to formatting MVC JSON output. The messageSource() bean provides localized web text to Thymeleaf pages. templateResolver, templateEngine and viewResolver are the methods most directly responsible for whether Thymeleaf will fire up sweetly for you, which we'll look at next.

Template Resolver, Engine and View Resolver Methods

Here are the guts of the three primary methods that configure Thymeleaf.

1) We're setting the location of Thymeleaf's templates. 2) The thing here is that to display text properties on Thymeleaf templates we need to set the Template Engine Message Source. 3) Remember ThymeleafViewResolver here.

The Home Thymeleaf Template

Thymeleaf has a lot going for it and I'm looking forward to much more fun with it in the future. Here's an excerpt from home.html that displays the page shown at the top of this post. You'll notice programming assistance for text properties isn't currently supported in IntelliJ. I spent hours on this until finding the Issue on JetBrain's support site. No biggie.

More Thymeleaf posts will no doubt be coming your way. The source code covered in this post can be found in my Spring-Data MVC application on GitHub, branch v0.1.3.

Posted June 11, 2015 06:01 PM EDT

More Like This Post