Spring Boot中ModelAndView映射失效及Thymeleaf Starter Bean创建失败求助
问题分析与解决方案
核心问题:依赖冲突与错误的依赖引入方式
你遇到的两个问题根源都是Thymeleaf依赖配置错误:
- 初始仅引入
thymeleaf核心包,缺少Spring Boot整合Thymeleaf必需的自动配置类,导致视图解析器无法正常工作,所以ModelAndView找不到模板。 - 后续直接添加
spring-boot-starter-thymeleaf但未移除原有核心包,导致版本冲突,触发Bean创建异常。
具体修复步骤
清理并修正依赖配置
删除手动指定版本的thymeleaf核心依赖,仅保留spring-boot-starter-thymeleaf和布局方言依赖(让Spring Boot自动管理版本,避免冲突):<!-- 移除原有单独的thymeleaf依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>nz.net.ultraq.thymeleaf</groupId> <artifactId>thymeleaf-layout-dialect</artifactId> </dependency>注:Spring Boot的starter已经包含了Thymeleaf核心包、视图解析器自动配置等组件,无需单独引入核心包。
确认模板路径与视图名匹配
你的模板文件路径src/main/resources/templates/user/new.html和Controller中指定的视图名user/new完全匹配,这部分是正确的,无需修改。可选:检查Thymeleaf自动配置(若有自定义配置)
Spring Boot默认会自动配置Thymeleaf,如果你在application.properties或application.yml中有自定义配置,确保没有覆盖关键设置:# 默认配置,无需手动添加,除非需要修改 spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.enabled=true
验证修复
重新启动应用,访问/new路由,应该能正常渲染Thymeleaf模板。
内容的提问来源于stack exchange,提问作者tolga
相关产品推荐
相关产品推荐

