Spring CLI(v2.1.3)用Grab注解无法加载依赖,实现ErrorController报错求助
解决Groovy Spring Boot中无法解析ErrorController的问题
你遇到的unable to resolve class ErrorController报错,主要是两个核心问题导致的:缺少Web模块依赖,以及未导入类的完整包路径。我来帮你一步步搞定:
问题根源分析
ErrorController属于Spring Boot Web模块的核心类,但你当前仅引入了spring-boot-autoconfigure,它只包含自动配置逻辑,并不包含Web相关的核心类;同时代码里没有显式导入该类的包路径,Groovy无法自动识别到这个类的位置。
具体解决方案
1. 调整依赖,引入Web Starter
把现有的@Grab依赖替换为spring-boot-starter-web,它会自动包含spring-boot-autoconfigure以及所有Web开发必需的依赖:
@Grab("spring-boot-starter-web")
2. 导入ErrorController类
在代码开头添加该类的完整包导入语句,让Groovy能准确定位到它:
import org.springframework.boot.web.servlet.error.ErrorController
修改后的完整代码
package org.test import org.springframework.boot.web.servlet.error.ErrorController import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController @Grab("spring-boot-starter-web") @RestController public class HelloController implements ErrorController{ @GetMapping(value="/hello") public String sayHello(){ return "Hey Joker"; } @Override public String getErrorPath(){ return "/error"; } @GetMapping(value="/error") public String notFoundException(){ return "{error:'NOT_FOUND', message:'Resource Not Found'}"; } }
验证运行效果
现在重新执行启动命令:
spring run restController.groovy
服务启动后:
- 访问
http://localhost:8080/hello会返回Hey Joker - 访问任意不存在的路径(比如
http://localhost:8080/test)会返回你定义的错误JSON:{error:'NOT_FOUND', message:'Resource Not Found'}
额外提一句:在Spring Boot 2.3及以上版本,官方更推荐用ErrorAttributes结合@ControllerAdvice来处理全局错误,但你的需求用ErrorController完全可以正常工作。
内容的提问来源于stack exchange,提问作者Abdelghani Roussi
相关产品推荐
相关产品推荐

