Thymeleaf是围绕自然模板的概念设计的,该模板允许进行静态原型制作:模板逻辑不会影响用作原型的模板。 尽管这是一项很棒的技术,但您可能还希望在运行的Spring Boot应用程序中查看结果,而不必每次更改Thymeleaf视图时都重新启动服务器。 此外,您可能希望所有其他静态资源(如JavaScript和CSS文件)也可以在开发期间重新加载。 如何用Spring Boot实现它?
Thymeleaf模板重新加载
在使用Thymeleaf视图引擎的Spring Boot应用程序上工作时,需要两个属性来确保重新加载模板: spring.thymeleaf.cache
和spring.thymeleaf.prefix
。 将spring.thymeleaf.cache
设置为false
将禁用模板缓存,而spring.thymeleaf.prefix
允许指定在构建视图URL时前缀为视图名称的前缀。
范例(Windows):
spring.thymeleaf.prefix=file:///C:/Projects/github/spring-boot-thymeleaf/src/main/resources/templates/
假设所有模板都在指定的路径中,则更改它们将需要刷新页面,而无需重新启动应用程序/服务器。
这两个属性都可以在开发配置文件中使用(例如,创建application-dev.properties
并在dev
配置文件处于活动状态时运行应用程序)。
重新加载静态资源(CSS,JavaScript)
使用Spring Boot和Thymeleaf在开发期间重新加载模板相对容易。 如果要重新加载CSS和JavaScript等静态资源,则方法非常相似:您需要使用spring.resources.static-locations
。
范例(Windows):
spring.resources.static-locations=file:///C:/Projects/github/spring-boot-thymeleaf//src/main/resources/static/
在上面的示例中,只有一个位置,但是该属性接受多个位置。
此外,您可以配置更多与静态资源相关的设置,例如缓存等。请参考Spring Boot文档并了解有关spring.resources.*
属性( http://docs.spring.io/spring-boot/docs /current/reference/html/common-application-properties.html )
application-dev.properties
最终的解决方案如下所示:
#
# Development profile with templates and static resources reloading
## Path to project
project.base-dir=file:///C:/Projects/github/spring-boot-thymeleaf# Templates reloading during development
spring.thymeleaf.prefix=${project.base-dir}/src/main/resources/templates/
spring.thymeleaf.cache=false# Static resources reloading during development
spring.resources.static-locations=${project.base-dir}/src/main/resources/static/
spring.resources.cache-period=0
注意:您可以在本文的源代码参考中找到它: HOW-TO:使用Maven的Spring Boot和Thymeleaf
如果您不想创建新的配置文件,则可以在运行应用程序时简单地将属性作为JVM选项( -D
)提供。
替代方法– Spring Boot DevTools
Spring Boot的模块之一是DevTools(从1.3版开始)。 在许多功能中,它无需重新配置即可实时重新加载Thymeleaf模板和静态资源。 它还支持LiveReload协议。
注意 :更改模板/资源时,请重新生成项目(在Windows上为CTRL + F9),然后刷新。 当您安装LiveReload插件(我使用Chrome的LiveReload插件进行了测试: https ://chrome.google.com/webstore/detail/livereload/jnihajbhpnppcggbcgedagnkighmdlei)后,页面会自动刷新。
在此处了解更多信息: https : //spring.io/blog/2015/06/17/devtools-in-spring-boot-1-3以及此处: https : //t.co/td23nP73mt
摘要
感谢本文中介绍的技术,您可以使Spring Boot应用程序的前端开发变得更加容易。 但是从生产环境中的类路径之外为您的Spring Boot应用程序提供Thymeleaf模板和静态资源的可能性也可能带来一些优势。 示例之一可能是分离后端和前端部署。
也可以看看
- 操作方法:Maven的Spring Boot和Thymeleaf
- GitHub上的Spring Boot和Thymeleaf与Maven
翻译自: https://www.javacodegeeks.com/2016/12/spring-boot-thymeleaf-reload-templates-static-resources-without-restarting-application.html