[spring-boot] thymeleaf 热交换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/crazyman2010/article/details/72794501

使用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:

@Configuration
public 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文件后可立即生效。
方法如下:

@Configuration
public 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;
    }
}

猜你喜欢

转载自blog.csdn.net/crazyman2010/article/details/72794501