Spring Boot 2.7.6中GET '/v3/test/'请求返回NoHandlerException问题
问题原因分析与解决建议
1. 控制器类命名不符合规范
你的控制器类名为test(首字母小写),Spring扫描组件时默认遵循Java类命名规范(首字母大写),可能导致该类未被识别为Spring Bean,无法注册请求映射。
解决方法:将类名改为Test(首字母大写),符合Java类命名规范:
@RestController @RequestMapping("/test") public class Test { // 控制器方法实现 }
2. 请求路径末尾斜杠的匹配问题
控制器映射路径是/test,但请求路径为/v3/test/(末尾带斜杠)。Spring MVC默认采用严格路径匹配策略,/test和/test/会被视为不同路径,导致找不到对应处理器。
解决方法:
- 调整请求路径,去掉末尾斜杠,改为
/v3/test - 或修改控制器映射路径为
/test/,与请求路径保持一致:@RestController @RequestMapping("/test/") public class Test { // 控制器方法实现 } - 或开启宽松路径匹配,在application.properties中添加配置:
spring.mvc.pathmatch.matching-strategy=PATH_PATTERN_PARSER spring.mvc.pathmatch.use-trailing-slash=true
3. 组件扫描范围未覆盖控制器
如果控制器所在包不在Spring Boot主启动类的默认扫描范围内(比如主启动类在com.example.demo,控制器在com.example.controller以外的包),Spring无法扫描到该控制器,自然无法注册请求映射。
解决方法:
- 将控制器类移到主启动类的子包下
- 或在主启动类上添加
@ComponentScan注解,指定控制器所在包:@SpringBootApplication @ComponentScan(basePackages = {"com.example.controller", "com.example.demo"}) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
4. Security配置的潜在拦截(可能性较低)
虽然你已配置SecurityFilterChain和WebSecurityCustomizer,但仍需确认是否允许/v3/test/**路径的访问。若Security拦截了该路径,虽通常返回403而非NoHandlerException,但也需排查:
解决方法:在SecurityFilterChain配置中明确放行该路径:
@Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers("/v3/test/**").permitAll() .anyRequest().authenticated() ) // 其他Security配置项 return http.build(); }
内容的提问来源于stack exchange,提问作者Test Email
相关产品推荐
相关产品推荐

