简体   繁体   English

在 Spring 启动应用程序中自动重新加载 Thymeleaf 模板

[英]Automatically reload Thymeleaf templates in Spring Boot app

In my Spring Boot (2.4.2) app, I have some Thymeleaf templates in the src/main/resources/templates directory.在我的 Spring Boot (2.4.2) 应用程序中,我在src/main/resources/templates目录中有一些 Thymeleaf 模板。 I have spring-boot-devtools installed which automatically reloads classes when the code changes.我安装了 spring-boot-devtools,它会在代码更改时自动重新加载类。

I would like the Thymeleaf templates to also be automatically reloaded when they are changed.我希望 Thymeleaf 模板在更改时也能自动重新加载。 I've tried adding the following to the local application configuration我尝试将以下内容添加到本地应用程序配置中

spring:
  thymeleaf:
    cache: false

But it doesn't seem to work, ie the templates are loaded only on startup, so I need to restart the serve after changing them.但这似乎不起作用,即模板仅在启动时加载,因此我需要在更改它们后重新启动服务。 How can I enable automatic reloading of the Thymeleaf templates?如何启用 Thymeleaf 模板的自动重新加载?

Update更新

In response to some of the comments: I run the app from IntelliJ IDEA.回应一些评论:我从 IntelliJ IDEA 运行应用程序。

If you're using IntelliJ, you have to rebuild the project (fn + shift + 9) on mac and (ctrl + shift + f9) on windows I believe.如果您使用的是 IntelliJ,您必须在 mac 上重建项目 (fn + shift + 9) 并在 windows 上重建项目 (ctrl + shift + f9) 我相信。 This can be kind of annoying, there might be some built in functionality in IntelliJ, or your IDEA of choice, to just rebuild when certain files are modified.这可能有点烦人,IntelliJ 或您选择的 IDEA 中可能有一些内置功能,可以在修改某些文件时重新构建。

Something like this should work.像这样的东西应该工作。 Instead of reading your templates from the built files (typically, in your /target folder), you can tell Thymeleaf to read them directly from your /resources folder.您可以告诉 Thymeleaf 直接从您的 /resources 文件夹中读取模板,而不是从构建文件中读取模板(通常在 /target 文件夹中)。 That way, you only need to hit F5 to refresh your browser.这样,您只需按 F5 即可刷新浏览器。

# Setup auto-reload of templates for Thymeleaf by disabling the Template Cache.
# This allows you to live-code on HTML without needing to restart the server.
spring:
  thymeleaf: # Thymeleaf
    cache: false
    mode: HTML
    encoding: UTF-8
    # change load path to resource folder instead of /target
    prefix: file:src/main/resources/templates/

  resources: # Static resources
    # change load path to resource folder instead of /target
    static-locations: file:src/main/resources/static/
    cache:
      period: 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM