一、Thymeleaf 概述
1、概述
- 開發傳統Java WEB工程時,我們可以使用JSP頁面模板語言,但是在SpringBoot中已經不推薦使用JSP了。
- Thymeleaf 是一個頁面展示的模板引擎,跟 Velocity、FreeMarker 類似
- Thymeleaf 是SpringBoot官方所推薦使用的
2、Thymeleaf 的特點
- 動靜結合:Thymeleaf 在有網絡和無網絡的環境下皆可運行,即它可以讓美工在瀏覽器查看頁面的靜態效果,也可以讓程序員在服務器查看帶數據的動態頁面效果。這是由於它支持 html 原型,然後在 html 標籤裏增加額外的屬性來達到模板+數據的展示方式。瀏覽器解釋 html 時會忽略未定義的標籤屬性,所以 thymeleaf 的模板可以靜態地運行;當有數據返回到頁面時,Thymeleaf 標籤會動態地替換掉靜態內容,使頁面動態顯示。
- 開箱即用:它提供標準和spring標準兩種方言,可以直接套用模板實現JSTL、 OGNL表達式效果,避免每天套模板、該jstl、改標籤的困擾。同時開發人員也可以擴展和創建自定義的方言。
- 多方言支持:Thymeleaf 提供spring標準方言和一個與 SpringMVC 完美集成的可選模塊,可以快速的實現表單綁定、屬性編輯器、國際化等功能。
- 與SpringBoot完美整合:SpringBoot提供了Thymeleaf的默認配置,並且爲Thymeleaf設置了視圖解析器,我們可以像以前操作jsp一樣來操作Thymeleaf。代碼幾乎沒有任何區別,就是在模板語法上有區別。
二、Thymeleaf 案例
第一步:引入 SpringBoot 相關構建
spring-boot-starter-parent
Spring Boot的父級依賴,表示當前的項目就是Spring Boot項目spring-boot-starter-web
導入web場景的所有依賴druid-spring-boot-starter
具有Druid支持的Spring Boot,可幫助您簡化Spring Boot中的Druid配置spring-boot-starter-jdbc
通過HikariCP連接池使用JDBC的入門mysql-connector-java
用於MySQL的JDBC 驅動程序mybatis-spring-boot-starter
SpringBoot 整合 MyBatisspring-boot-starter-test
導入junit 測試的所有依賴mapper-spring-boot-starter
通用Mapper啓動器
第二步:編寫 Spring Boot 啓動類 Application.java
package cn.lemon;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan("cn.lemon.dao")/*@MapperScan("dao所在的包"),自動搜索包中的接口,產生dao的代理對象*/
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
第三步:在 resource 中新建 application.properties 配置文件
#修改端口爲 ;1000,系統默認端口爲:8080
server.port=1000
#如果想在控制檯打印日誌是需要配置的,因爲我們記錄的log級別是debug,默認是顯示info以上
#SpringBoot通過`logging.level.*=debug`來配置日誌級別,*填寫包名
logging.level.cn.lemon=debug
#數據庫連接配置
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/springboot
jdbc.username=root
jdbc.password=lemon
# mybatis 別名掃描
mybatis.type-aliases-package=cn.lemon.domain
# mapper.xml文件位置,如果沒有映射文件,請註釋掉
mybatis.mapper-locations=classpath:mappers/*.xml
第四步:編寫 JdbcConfig.java ,用於讀取屬性文件 application.properties(默認讀取)
package cn.lemon.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class JdbcConfig {
@Bean
@ConfigurationProperties(prefix = "jdbc")
public DataSource dataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
return druidDataSource;
}
}
第五步:新建實體類 User.java,對應數據庫表
package cn.lemon.domain;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
@Table(name = "tb_user")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")/*可以省略*/
private Integer id;
@Column(name = "user_name")
private String userName;
private String password;
private String name;
private Integer age;
private Integer sex;
private Date birthday;
private Date created;
private Date updated;
private String note;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
第六步:新建數據訪問層dao 中的接口 UserDao.java
package cn.lemon.dao;
import cn.lemon.domain.User;
import tk.mybatis.mapper.common.Mapper;
public interface UserDao extends Mapper<User> {
}
第七步:編寫測試類,測試一下 UserDao.java
package cn.lemon.dao;
import cn.lemon.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserDaoTest {
@Autowired
private UserDao userDao;
@Test
public void testFindAll() {
List<User> userList = userDao.selectAll();
for (User user : userList) {
System.out.println(user.getId() + "\t" + user.getUserName() + "\t" + user.getPassword());
}
}
}
第八步:添加攔截器(也可以不添加)
首先我們定義一個攔截器:
package cn.lemon.interceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
private Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.debug("處理器執行之前執行");
return true;/*若返回 false,處理器不會跳轉*/
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
logger.debug("處理器執行之後執行");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
logger.debug("完成頁面跳轉後執行");
}
}
然後定義配置類,註冊攔截器:
package cn.lemon.config;
import cn.lemon.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
/**
* 通過@Bean註解,將我們定義的攔截器註冊到Spring容器
*/
@Bean
public LoginInterceptor loginInterceptor() {
return new LoginInterceptor();
}
/**
* 重寫接口中的addInterceptors方法,添加自定義攔截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 通過registry來註冊攔截器,通過addPathPatterns來添加攔截路徑
registry.addInterceptor(this.loginInterceptor()).addPathPatterns("/**");
}
}
第九步:編寫控制器controller/UserController.java
package cn.lemon.controller;
import cn.lemon.dao.UserDao;
import cn.lemon.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.List;
@Controller
public class UserController {
@Autowired
private UserDao userDao;
@GetMapping("/all")
public String findUserAll(Model model) {
List<User> userList = userDao.selectAll();//查詢所有用戶
model.addAttribute("users", userList);
return "users";
}
}
第十步:引入啓動器
spring-boot-starter-thymeleaf
SpringBoot會自動爲Thymeleaf註冊一個視圖解析器,與解析JSP的InternalViewResolver類似,Thymeleaf也會根據前綴和後綴來確定模板文件的位置:
- 默認前綴:
classpath:/templates/
- 默認後綴:
.html
所以如果我們返回視圖:users
,會指向到 classpath:/templates/users.html
第十一步:編寫 users.html 靜態頁面
- 根據上面的代碼,模板默認放在classpath下的templates文件夾中
- 注意:把html 的名稱空間,改成:
xmlns:th="http://www.thymeleaf.org"
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>首頁</title>
<style type="text/css">
table {border-collapse: collapse; font-size: 14px; width: 80%; margin: auto}
table, th, td {border: 1px solid darkslategray;padding: 10px}
</style>
</head>
<body>
<div style="text-align: center">
<span style="color: darkslategray; font-size: 30px">歡迎光臨!</span>
<hr/>
<table class="list">
<tr>
<th>編號</th>
<th>姓名</th>
<th>用戶名</th>
<th>年齡</th>
<th>性別</th>
<th>生日</th>
<th>備註</th>
</tr>
<!--
- ${} :這個類似與el表達式,但其實是ognl的語法,比el表達式更加強大
- th- 指令:th- 是利用了Html5中的自定義屬性來實現的。如果不支持H5,可以用`data-th-`來代替
- th:each :類似於`c:foreach` 遍歷集合,但是語法更加簡潔
- th:text :聲明標籤中的文本
- 例如`<td th-text='${user.id}'>1</td>`,如果user.id有值,會覆蓋默認的1
- 如果沒有值,則會顯示td中默認的1。這正是thymeleaf能夠動靜結合的原因,模板解析失敗不影響頁面的顯示效果,因爲會顯示默認值!
-->
<tr th:each="user : ${users}">
<td th:text="${user.id}">1</td>
<td th:text="${user.name}">張三</td>
<td th:text="${user.userName}">zhangsan</td>
<td th:text="${user.age}">20</td>
<td th:text="${user.sex} == 1 ? '男': '女'">男</td>
<td th:text="${#dates.format(user.birthday, 'yyyy-MM-dd')}">1980-02-30</td>
<td th:text="${user.note}">1</td>
</tr>
</table>
</div>
</body>
</html>
第十二步:運行,測試
三、Thymeleaf 模板緩存
Thymeleaf會在第一次對模板解析之後進行緩存,極大的提高了併發處理能力。但是這給我們開發帶來了不便,修改頁面後並不會立刻看到效果,我們開發階段可以關掉緩存使用:
#開發階段關閉thymeleaf的模板緩存
spring.thymeleaf.cache=false
注意:
- 在IDEA中,我們需要在修改頁面後按快捷鍵:
Ctrl + Shift + F9
對項目進行rebuild纔可以。
四、Thymeleaf 詳解
1、標準表達式語法——變量表達式
- 變量表達式即OGNL表達式或Spring EL表達式(在Spring術語中也叫model attributes)。如:
${session.user.name}
- 它們將以HTML標籤的一個屬性來表示:
<span th:text="${book.author.name}">
<li th:each="book : ${books}">
2、標準表達式語法——選擇或星號表達式
- 選擇表達式很像變量表達式,不過它們用一個預先選擇的對象來代替上下文變量容器(map)來執行,如:
*{customer.name}
- 被指定的object由th:object屬性定義:
<div th:object="${book}">
...
<span th:text="*{title}">...</span>
...
</div>
3、標準表達式語法——URL表達式
- URL表達式指的是把一個有用的上下文或回話信息添加到URL,這個過程經常被叫做URL重寫:
@{/order/list}
- URL還可以設置參數:
@{/order/details(id=${orderId})}
- 相對路徑:
@{../documents/report}
讓我們看這些表達式:
<form th:action="@{/createOrder}">
<a href="main.html" th:href="@{/main}">
4、變量表達式和星號表達的什麼區別
- 如果不考慮上下文的情況下,兩者沒有區別;星號語法評估在選定對象上表達,而不是整個上下文,什麼是選定對象?就是父標籤的值,如下:
<div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>
這是完全等價於:
<div th:object="${session.user}">
<p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>
當然,美元符號和星號語法可以混合使用:
<div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>
5、表達式支持的語法
5-1、字面(Literals)
- 文本文字(Text literals):
'one text', 'Another one!',…
- 數字文本(Number literals):
0, 34, 3.0, 12.3,…
- 布爾文本(Boolean literals):
true, false
- 空(Null literal):
null
- 文字標記(Literal tokens):
one, sometext, main,…
5-2、文本操作(Text operations)
- 字符串連接(String concatenation):
+
- 文本替換(Literal substitutions):
|The name is ${name}|
5-3、算術運算(Arithmetic operations)
- 二元運算符(Binary operators):
+, -, *, /, %
- 減號(單目運算符)Minus sign (unary operator):
-
5-4、布爾操作(Boolean operations)
- 二元運算符(Binary operators):
and, or
- 布爾否定(一元運算符)Boolean negation (unary operator):
!, not
5-5、比較和等價(Comparisons and equality)
- 比較(Comparators):
>, <, >=, <= (gt, lt, ge, le)
- 等值運算符(Equality operators):
==, != (eq, ne)
5-6、條件運算符(Conditional operators)
- If-then:
(if) ? (then)
- If-then-else:
(if) ? (then) : (else)
- Default: (value) ?:
(defaultvalue)
所有這些特徵可以被組合並嵌套:
'User is of type ' + (${user.isAdmin()} ? 'Administrator' : (${user.type} ?: 'Unknown'))
五、常用的 th 標籤
還有非常多的標籤,這裏只列出最常用的幾個,由於一個標籤內可以包含多個th:x屬性,其生效的優先級順序爲:include,each,if/unless/switch/case,with,attr/attrprepend/attrappend,value/href,src ,etc,text/utext,fragment,remove
六、常用的使用方法
1、賦值、字符串拼接
<p th:text="${collect.description}">description</p>
<span th:text="'Welcome to our application, ' + ${user.name} + '!'">
字符串拼接還有另外一種簡潔的寫法:
<span th:text="|Welcome to our application, ${user.name}!|">
2、條件判斷 If/Unless
Thymeleaf中使用th:if和th:unless屬性進行條件判斷,下面的例子中,<a>
標籤只有在th:if
中條件成立時才顯示:
<a th:if="${myself=='yes'}" > </i> </a>
<a th:unless=${session.user != null} th:href="@{/login}" >Login</a>
th:unless於th:if恰好相反,只有表達式中的條件不成立,纔會顯示其內容。
也可以使用 (if) ? (then) : (else)
這種語法來判斷顯示的內容
3、for 循環
<tr th:each="collect,iterStat : ${collects}">
<th scope="row" th:text="${collect.id}">1</th>
<td >
<img th:src="${collect.webLogo}"/>
</td>
<td th:text="${collect.url}">Mark</td>
<td th:text="${collect.title}">Otto</td>
<td th:text="${collect.description}">@mdo</td>
<td th:text="${terStat.index}">index</td>
</tr>
iterStat
稱作狀態變量,屬性有:
- index:當前迭代對象的index(從0開始計算)
- count: 當前迭代對象的index(從1開始計算)
- size:被迭代對象的大小
- current:當前迭代變量
- even/odd:布爾值,當前循環是否是偶數/奇數(從0開始計算)
- first:布爾值,當前循環是否是第一個
- last:布爾值,當前循環是否是最後一個
4、URL
URL在Web應用模板中佔據着十分重要的地位,需要特別注意的是Thymeleaf對於URL的處理是通過語法@{…}
來處理的。 如果需要Thymeleaf對URL進行渲染,那麼務必使用th:href
,th:src
等屬性,下面是一個例子:
<!-- Will produce 'http://localhost:8080/standard/unread' (plus rewriting) -->
<a th:href="@{/standard/{type}(type=${type})}">view</a>
<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>
設置背景
<div th:style="'background:url(' + @{/<path-to-image>} + ');'"></div>
根據屬性值改變背景:
<div class="media-object resource-card-image" th:style="'background:url(' + @{(${collect.webLogo}=='' ? 'img/favicon.png' : ${collect.webLogo})} + ')'" ></div>
說明:
- 上例中URL最後的
(orderId=${o.id})
表示將括號內的內容作爲URL參數處理,該語法避免使用字符串拼接,大大提高了可讀性 @{...}
表達式中可以通過{orderId}
訪問Context中的orderId變量@{/order}
是Context相關的相對路徑,在渲染時會自動添加上當前Web應用的Context名字,假設context名字爲app,那麼結果應該是/app/order
5、內聯js
內聯文本:[[…]]
內聯文本的表示方式,使用時,必須先用th:inline=”text/javascript/none”
激活,th:inline
可以在父級標籤內使用,甚至作爲body的標籤。內聯文本儘管比th:text
的代碼少,不利於原型顯示。
js附加代碼:
/*[+
var msg = 'This is a working application';
+]*/
js移除代碼:
/*[- */
var msg = 'This is a non-working template';
/* -]*/
6、內嵌變量
爲了模板更加易用,Thymeleaf還提供了一系列Utility對象(內置於Context中),可以通過#
直接訪問:
- dates : java.util.Date**的功能方法類。
- calendars : 類似
#dates
,面向java.util.Calendar - numbers : 格式化數字的功能方法類
- strings : 字符串對象的功能類,contains,startWiths,prepending/appending等等
- objects: 對objects的功能類操作
- bools: 對布爾值求值的功能方法
- arrays:對數組的功能類方法
- lists: 對lists功能類方法
- sets
- maps
…
下面用一段代碼來舉例一些常用的方法:
dates
/*
* Format date with the specified pattern
* Also works with arrays, lists or sets
*/
${#dates.format(date, 'dd/MMM/yyyy HH:mm')}
${#dates.arrayFormat(datesArray, 'dd/MMM/yyyy HH:mm')}
${#dates.listFormat(datesList, 'dd/MMM/yyyy HH:mm')}
${#dates.setFormat(datesSet, 'dd/MMM/yyyy HH:mm')}
/*
* Create a date (java.util.Date) object for the current date and time
*/
${#dates.createNow()}
/*
* Create a date (java.util.Date) object for the current date (time set to 00:00)
*/
${#dates.createToday()}
strings
/*
* Check whether a String is empty (or null). Performs a trim() operation before check
* Also works with arrays, lists or sets
*/
${#strings.isEmpty(name)}
${#strings.arrayIsEmpty(nameArr)}
${#strings.listIsEmpty(nameList)}
${#strings.setIsEmpty(nameSet)}
/*
* Check whether a String starts or ends with a fragment
* Also works with arrays, lists or sets
*/
${#strings.startsWith(name,'Don')} // also array*, list* and set*
${#strings.endsWith(name,endingFragment)} // also array*, list* and set*
/*
* Compute length
* Also works with arrays, lists or sets
*/
${#strings.length(str)}
/*
* Null-safe comparison and concatenation
*/
${#strings.equals(str)}
${#strings.equalsIgnoreCase(str)}
${#strings.concat(str)}
${#strings.concatReplaceNulls(str)}
/*
* Random
*/
${#strings.randomAlphanumeric(count)}
七、使用thymeleaf佈局
使用thymeleaf佈局非常的方便
在/resources/templates/目錄下創建footer.html,內容如下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="copy(title)">
© 2011 The Good Thymes Virtual Grocery
<span th:text="${title}">abcdefa234234</span>
</div>
</body>
</html>
在頁面任何地方引入:
<body>
<div th:include="footer:: copy('pbj44')"></div>
<div th:replace="footer:: copy('pbj44')"></div>
</body>
th:include
和 th:replace
區別,include只是加載,replace是替換
返回的HTML如下:
<body>
<div> © 2016 </div>
<footer>© 2016 </footer>
</body>
下面是一個常用的後臺頁面佈局,將整個頁面分爲頭部,尾部、菜單欄、隱藏欄,點擊菜單隻改變content區域的頁面
<body class="layout-fixed">
<div th:fragment="navbar" class="wrapper" role="navigation">
<div th:replace="fragments/header:: header">Header</div>
<div th:replace="fragments/left:: left">left</div>
<div th:replace="fragments/sidebar:: sidebar">sidebar</div>
<div layout:fragment="content" id="content" ></div>
<div th:replace="fragments/footer:: footer">footer</div>
</div>
</body>
八、單元測試(瞭解)
pom.xml中加載測試啓動器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
測試類:
@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloControllerTest {
private MockMvc mvc;
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
}
@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("hello spring boot2")));
}
@Test
public void getHello2() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
}
mockmv常用的用法:
- mockMvc.perform執行一個請求;
- MockMvcRequestBuilders.get("/user/1")構造一個請求
- ResultActions.andExpect添加執行完成後的斷言
- ResultActions.andDo添加一個結果處理器,表示要對結果做點什麼事情,比如此處使用MockMvcResultHandlers.print()輸出整個響應結果信息。
- ResultActions.andReturn表示執行完成後返回相應的結果。
九、開發環境的調試
熱啓動在正常開發項目中已經很常見了吧,雖然平時開發web項目過程中,改動項目啓重啓總是報錯;但springBoot對調試支持很好,修改之後可以實時生效,需要添加以下的配置:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
該模塊在完整的打包環境下運行的時候會被禁用。如果你使用java -jar啓動應用或者用一個特定的classloader啓動,它會認爲這是一個“生產環境”。
在application.yml文件加入spring:thymeleaf:cache: false 配置
如果你通過上面的步驟還沒實現想要的熱部署效果,可以繼續做以下兩個配置:
1、開啓Java Compiler的自動build
2、按住Ctrl + Shift +Alt + /
選擇Registry,按照下圖標註配置
或者不進行熱部署配置直接點Ctrl+F9