无法运行集成Thymeleaf的Spring Boot应用,请求排查问题
我来帮你一步步梳理这个问题,从报错Cannot find template location: classpath:/templates/来看,核心是Spring Boot启动时没扫描到你的模板目录或文件,进而导致Thymeleaf无法渲染页面。咱们从几个关键维度排查:
1. 先确认项目目录结构是否完全正确
Spring Boot对资源目录的位置有严格约定,你的welcome.html必须放在**src/main/resources/templates/**下,注意是src/main/resources,不是src/resources或者其他路径,很多新手容易犯拼写错误(比如把templates写成template少了s)或者目录层级错放。
正确的目录结构应该是这样:
your-project/ ├─ src/ │ ├─ main/ │ │ ├─ java/ │ │ │ └─ com/ │ │ │ └─ sopra/ │ │ │ └─ springBoot/ │ │ │ ├─ Application.java │ │ │ └─ HomeController.java │ │ └─ resources/ │ │ ├─ templates/ │ │ │ └─ welcome.html │ │ └─ application.properties(可选) │ └─ test/ └─ pom.xml
2. 检查pom.xml的配置细节
你的pom.xml已经引入了spring-boot-starter-thymeleaf依赖,这点没问题,但有两个小细节要注意:
- 你用的Spring Boot版本是
1.3.6.RELEASE,这个版本比较老旧(2016年发布),虽然能运行,但可能存在一些资源扫描的小bug,建议如果可以的话升级到2.x系列的稳定版本;如果不想大改,先执行mvn clean package重新打包,再运行jar包试试,有时候旧版本打包会漏掉资源文件。 spring-boot-maven-plugin配置是正确的,它负责把resources目录下的文件打包到classpath中,确保这个插件没有被注释或配置错误。
3. 手动指定Thymeleaf模板位置(强制生效)
可以在src/main/resources下新建application.properties文件,手动配置Thymeleaf的模板前缀和后缀,强制Spring Boot扫描指定目录:
spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html
添加后重启项目,看是否能识别到模板。
4. 检查IDE的资源目录标记
如果你用IntelliJ IDEA或Eclipse,要确保src/main/resources被标记为资源根目录:
- IDEA:右键
resources目录 →Mark Directory as→Resources Root - Eclipse:右键项目 →
Properties→Java Build Path→Source→ 选中src/main/resources,确认它在Source folders列表中,输出目录配置正确。
5. 确认控制器和模板文件名的一致性
你的HomeController返回的是"welcome",Thymeleaf会自动拼接成classpath:/templates/welcome.html,这里要注意文件名大小写敏感,如果你的模板文件是Welcome.html或者welcome.HTML,都会导致找不到,必须完全匹配。
ThymeleafAutoConfiguration是Spring Boot自动配置Thymeleaf的核心类,排查它可以从这几点入手:
- 查看启动日志:搜索日志中的
ThymeleafAutoConfiguration,如果看到ConditionalOnClass found required class 'org.thymeleaf.spring4.SpringTemplateEngine',说明配置类被正常加载;如果出现ConditionalOnClass did not find required class,说明spring-boot-starter-thymeleaf依赖没有正确引入。 - 确认自动配置开关:你的
@SpringBootApplication已经包含了@EnableAutoConfiguration,所以自动配置是开启的,不用额外添加,但如果之前自定义过配置类,要确保没有覆盖Thymeleaf的默认配置。 - 调试查看配置参数:可以在启动类中注入
ThymeleafProperties,打印它的prefix和suffix属性,确认是否是预期的classpath:/templates/和.html:
@Autowired private ThymeleafProperties thymeleafProperties; @PostConstruct public void printThymeleafConfig() { System.out.println("Thymeleaf prefix: " + thymeleafProperties.getPrefix()); System.out.println("Thymeleaf suffix: " + thymeleafProperties.getSuffix()); }
按照上面的步骤逐一排查,大概率是目录结构或IDE标记的问题,先从最基础的目录检查起,这是新手最容易踩的坑。
内容的提问来源于stack exchange,提问作者R.Sehdev

