[spring-boot] thymeleaf 热交换

来源:互联网 发布:苹果mac装win7系统 编辑:程序博客网 时间:2024/05/04 13:07

使用spring boot main方法启动时,修改了thymeleaf文件后,热交换不能起作用,每次修改都需要重新启动服务,非常不方便,google搜索到方法,特分享于此。
原文:https://github.com/spring-projects/spring-boot/issues/34

The default template resolver registered by spring is classpath based, meaning that it loads the templates from the compiled resources. That’s why it requires a recompilation. Thymeleaf includes a file-system based resolver, this loads the templates from the file-system directly not through the classpath (compiled resources). Spring Boot allows us to override the default resolver by making a bean with the name defaultTemplateResolver, here is a full example:

@Configurationpublic class ThymeleafConfiguration {  @Bean  public ITemplateResolver defaultTemplateResolver() {    TemplateResolver resolver = new FileTemplateResolver();    resolver.setSuffix(".html");    resolver.setPrefix("path/to/your/templates");    resolver.setTemplateMode("HTML5");    resolver.setCharacterEncoding("UTF-8");    resolver.setCacheable(false);    return resolver;  }}

大意是默认情况下,spring boot是使用class path寻找thymeleaf文件的,所以加载的是已编译好的thymeleaf文件。spring boot 允许使用file system based resolver 从文件系统加载thymeleaf文件,所以只要配置使用file system based resolver,修改thymeleaf文件后可立即生效。
方法如下:

@Configurationpublic class ThymeleafConfig {    @Bean    public ITemplateResolver defaultTemplateResolver() {        TemplateResolver resolver = new FileTemplateResolver();        resolver.setSuffix(".html");        resolver.setPrefix("src/main/resources/templates/");        resolver.setTemplateMode("HTML5");        resolver.setCharacterEncoding("UTF-8");        resolver.setCacheable(false);        return resolver;    }}