Web: Spring 4 & Thymeleaf Hot Cache

You might have run into a problem with using Thymeleaf and Spring 4 configuration where your changes to a┬áThymeleaf template are not immediately reflected on the page after refreshing it. Quite annoying especially as it worked ok with JSP’s right? To fix it adopt the following

/**
 * Web configuration.
 *
 */
// Marks this class as configuration
@Configuration
// Specifies which package to scan
@ComponentScan("com.netthreads.example")
// Enables Spring's annotations
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter
{
	public static final String DEFAULT_PREFIX = "/WEB-INF/templates/";
	public static final String DEFAULT_SUFFIX = ".html";
	public static final String DEFAULT_MODE = "HTML5";
	public static final String[] DEFAULT_VIEW_NAMES =
	{
		"*"
	};

	// Hot re-load, false=will reload changes.
	public static final boolean DEFAULT_CACHE = false;

	@Bean
	public ServletContextTemplateResolver templateResolver()
	{
		ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
		resolver.setPrefix(DEFAULT_PREFIX);
		resolver.setSuffix(DEFAULT_SUFFIX);
		resolver.setTemplateMode(DEFAULT_MODE);

		return resolver;
	}

	@Bean
	public SpringTemplateEngine templateEngine()
	{
		SpringTemplateEngine engine = new SpringTemplateEngine();
		engine.setTemplateResolver(templateResolver());

		// Need this for hot re-load
		if (!DEFAULT_CACHE)
		{
			engine.setCacheManager(null);
		}

		return engine;
	}

	@Bean
	public ViewResolver viewResolver()
	{
		ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
		viewResolver.setTemplateEngine(templateEngine());
		viewResolver.setOrder(1);
		viewResolver.setCache(DEFAULT_CACHE);
		viewResolver.setViewNames(DEFAULT_VIEW_NAMES);

		return viewResolver;
	}

	@Bean
	@Description("Spring message resolver")
	public ResourceBundleMessageSource messageSource()
	{
		ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
		messageSource.setBasename("messages");

		return messageSource;
	}

	/**
	 * Add our static resources folder mapping.
	 *
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry)
	{
		registry.addResourceHandler("/static/**").addResourceLocations("/static/");
	}
}

See the bits concerned with DEFAULT_CACHE. Copy these and you will find your changes reflected right away just like good old JSP!

Comments

Leave a Reply