javascript
Spring Boot和Thymeleaf:重新加载模板和静态资源,而无需重新启动应用程序
Thymeleaf是圍繞自然模板的概念設(shè)計的,該模板允許進行靜態(tài)原型制作:模板邏輯不會影響用作原型的模板。 盡管這是一項很棒的技術(shù),但您可能還希望在運行的Spring Boot應(yīng)用程序中查看結(jié)果,而不必每次更改Thymeleaf視圖時都重新啟動服務(wù)器。 此外,您可能希望所有其他靜態(tài)資源(如JavaScript和CSS文件)也可以在開發(fā)期間重新加載。 如何用Spring Boot實現(xiàn)它?
Thymeleaf模板重新加載
在使用Thymeleaf視圖引擎的Spring Boot應(yīng)用程序上工作時,需要兩個屬性來確保重新加載模板: spring.thymeleaf.cache和spring.thymeleaf.prefix 。 將spring.thymeleaf.cache設(shè)置為false將禁用模板緩存,而spring.thymeleaf.prefix允許指定在構(gòu)建視圖URL時前綴為視圖名稱的前綴。
范例(Windows):
spring.thymeleaf.prefix=file:///C:/Projects/github/spring-boot-thymeleaf/src/main/resources/templates/假設(shè)所有模板都在指定的路徑中,則更改它們將需要刷新頁面,而無需重新啟動應(yīng)用程序/服務(wù)器。
這兩個屬性都可以在開發(fā)配置文件中使用(例如,創(chuàng)建application-dev.properties并在dev配置文件處于活動狀態(tài)時運行應(yīng)用程序)。
重新加載靜態(tài)資源(CSS,JavaScript)
使用Spring Boot和Thymeleaf在開發(fā)期間重新加載模板相對容易。 如果要重新加載CSS和JavaScript等靜態(tài)資源,則方法非常相似:您需要使用spring.resources.static-locations 。
范例(Windows):
spring.resources.static-locations=file:///C:/Projects/github/spring-boot-thymeleaf//src/main/resources/static/在上面的示例中,只有一個位置,但是該屬性接受多個位置。
此外,您可以配置更多與靜態(tài)資源相關(guān)的設(shè)置,例如緩存等。請參考Spring Boot文檔并了解有關(guān)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
如果您不想創(chuàng)建新的配置文件,則可以在運行應(yīng)用程序時簡單地將屬性作為JVM選項( -D )提供。
替代方法– Spring Boot DevTools
Spring Boot的模塊之一是DevTools(從1.3版開始)。 在許多功能中,它無需重新配置即可實時重新加載Thymeleaf模板和靜態(tài)資源。 它還支持LiveReload協(xié)議。
注意 :更改模板/資源時,請重新生成項目(在Windows上為CTRL + F9),然后刷新。 當(dāng)您安裝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
摘要
感謝本文中介紹的技術(shù),您可以使Spring Boot應(yīng)用程序的前端開發(fā)變得更加容易。 但是從生產(chǎn)環(huán)境中的類路徑之外為您的Spring Boot應(yīng)用程序提供Thymeleaf模板和靜態(tài)資源的可能性也可能帶來一些優(yōu)勢。 示例之一可能是分離后端和前端部署。
也可以看看
- 操作方法: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
總結(jié)
以上是生活随笔為你收集整理的Spring Boot和Thymeleaf:重新加载模板和静态资源,而无需重新启动应用程序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 防御DDOS服务器(送DDoS防御服务器
- 下一篇: gradle idea java ssm