在 Spring Boot 项目中使用 Thymeleaf 时,通常情况下,你需要配置热加载(Hot Reload)来在开发过程中更快速地看到页面的变化。

发布于:2024-12-08 ⋅ 阅读:(168) ⋅ 点赞:(0)

配置步骤:

1. 添加 DevTools 依赖

pom.xml 中添加 spring-boot-devtools 依赖。DevTools 提供了自动重启、LiveReload、模板热加载等功能。

<dependencies>
    <!-- Spring Boot DevTools (用于热加载) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>  
        <!--代表 spring-boot-devtools 只会在开发环境中使用,在生产环境中不会被包含。-->
    </dependency>

    <!-- Thymeleaf 依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

    <!-- 其他依赖 -->
</dependencies>
2. 配置 Thymeleaf 模板热加载

Spring Boot 默认启用了热加载,但是需要做一些调整,以确保模板能正确地被热加载。

禁用缓存: 你需要禁用 Thymeleaf 模板的缓存,这样才能在每次修改模板时重新加载。你可以通过配置文件来实现.

# 禁用 Thymeleaf 缓存
spring.thymeleaf.cache=false

启用模板热加载: Spring Boot DevTools 默认启用模板的热加载,因此你不需要做额外的配置。如果你需要更高的自定义,可以通过以下方式显式配置模板加载器。 

# 启用 DevTools 模板热加载
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8

3. 开启 LiveReload(可选)

LiveReload 是 DevTools 提供的一个功能,能在文件修改后自动刷新浏览器。它可以帮助你在开发时看到实时预览。

 # 启用 LiveReload
spring.devtools.livereload.enabled=true


网站公告

今日签到

点亮在社区的每一天
去签到