spring boot 开发中禁用thyemeleaf模板/js/css等缓存

spring boot 开发中禁用thyemeleaf模板/js/css等缓存

一、Spring boot资源文件重载

    本文主要讲解spring boot开发web的一个技巧,开发过程中如何跳过thyemeleaf模板缓存、CSS/JS/图片等静态资源缓存。

    Spring Boot  ThyemeLeaf模板引擎自动装载的路径是基于classpath。这就等于他是从编译后的目录(target/classpath:/**)去加载模板和其他静态资源。
spring boot项目结构

默认情况下,我们可以通过以下几种方式去重新加载资源文件(js/css/html等)

  • 1.每次编辑资源文件后重启应用程序(显然这并不是一个很好的解决办法);
  • 2.使用IntelliJ上的CTRL + F9重新编译资源,或者(如果使用eclipse键映射,则按CTRL + SHIFT + F9)或简单地右键单击并单击编译

二、是否有更好的解决spring boot资源文件重新加载的办法?

首先我们得了解spring boot加载资源的逻辑


Thymeleaf包含一个基于文件系统的解析器,它直接从文件系统加载模板而不是通过类路径(编译资源)。


请参阅DefaultTemplateResolverConfiguration#defaultTemplateResolver的片段

@Bean
public SpringResourceTemplateResolver defaultTemplateResolver() {
 SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
 resolver.setApplicationContext(this.applicationContext);
 resolver.setPrefix(this.properties.getPrefix());

其中属性前缀默认为“classpath:/template/”. 请参阅片段ThymeleafProperties#DEFAULT_PREFIX

public static final String DEFAULT_PREFIX = "classpath:/templates/";

三、更好的Spring boot资源重载解决办法

3.1 解决spring boot thymeleaf模板引擎缓存问题

Spring Boot允许我们
覆盖属性’spring.thymeleaf.prefix’以指向源文件夹’src/main/resources/templates/’替换掉默认的‘classpath:/templates/’,操作如下

编辑文件application.yml|properties

$title(application.yml)
spring:
    thymeleaf:
        prefix: file:src/main/resources/templates/  #直接去更新目录读取模板而不是编译后的target目录

上面的配置将会告诉编译器不要去查找target/目录。并且你每次修改html 模板文件(模板文件存放于src/main/resources/template目录)都不需要重启应用程序。

3.2解决JavaScript/CSS等资源文件加载问题

您可以设置’spring.resources.static-locations’以指向您的静态资源文件夹(保存js / css,图像等)

$title(application.yml)
spring:
    resources:
        static-locations: file:src/main/resources/static/ #与上面相同的概念
          period: 0

四、完美的使用方式

application-dev.yml

$title(application-dev.yml)
spring:
    profiles:
        active: dev
    thymeleaf:
        cache: false        
        prefix: file:src/main/resources/templates/
        static-locations: file:src/main/resources/static/
            period: 0

application-prod.yml (生产环境不用覆盖默认的配置)

$title(application-prod.yml)
spring:
    profiles:
        active: prod

 

spring boot 开发中禁用thyemeleaf模板/js/css等缓存

相关文章:

你感兴趣的文章:

标签云: