SpringBoot 3.2.2无法访问@Controller方法,组件扫描配置无效求助
问题解决:SpringBoot接口404排查与修复
核心问题分析
你遇到的404本质是SpringBoot未扫描到Controller类,再加上主类启动代码存在低级错误,直接导致组件加载逻辑异常:
- 启动类指定错误:主类
NotificationsApplication的main方法里,写的是SpringApplication.run(NawaNotificationsApplication.class, args);,但你的类名是NotificationsApplication,这会让SpringBoot无法识别正确的主配置类,彻底打乱组件扫描逻辑。 - 包扫描范围未覆盖Controller:
@SpringBootApplication默认只扫描主类所在的notifications包及其子包,但你的Controller在service模块的独立包下,不在默认扫描范围内——之前加的@ComponentScan没生效,大概率是包路径配置错误,或者被启动类的错误掩盖了效果。
修复步骤
1. 修正主类启动代码+配置正确的扫描范围
把main方法里的启动类改成当前类本身,同时显式配置组件和DAO的扫描路径:
package notifications; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories; @SpringBootApplication // 替换成你实际的包路径:主类所在包、Controller所在包、DAO所在包 @ComponentScan(basePackages = {"notifications", "你的Controller所在包全路径", "你的DAO所在包全路径"}) // 显式指定R2DBC仓库的扫描路径,对应dao模块的包 @EnableR2dbcRepositories(basePackages = "你的DAO所在包全路径") public class NotificationsApplication { public static void main(String[] args) { // 修正为当前类 SpringApplication.run(NotificationsApplication.class, args); } }
2. 确认并替换实际包路径
比如你的Controller如果在com.yourproject.service.controller包下,就把这个路径加到@ComponentScan的basePackages数组里;DAO如果在com.yourproject.dao包下,就把这个路径填入@EnableR2dbcRepositories的basePackages参数。
3. 简化Controller注解(可选)
你当前用@Controller+@ResponseBody是有效的,也可以直接换成@RestController简化代码:
import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController // 替代@Controller+@ResponseBody @RequiredArgsConstructor @RequestMapping("/api") public class NotificationController { private final NotificationService notificationService; @GetMapping(value = "/hello", produces = "text/xml;charset=UTF-8") public ResponseEntity<String> hello() { return new ResponseEntity<>("Your response...", HttpStatus.OK); } }
验证修复
启动应用后,直接访问localhost:8080/api/hello,即可正常获取响应。
内容的提问来源于stack exchange,提问作者mtmx
相关产品推荐
相关产品推荐

