Spring Boot中@Path可正常使用 替换为@RequestMapping返回404如何解决
问题原因
你之前使用的@Path是JAX-RS规范的注解,适配Jersey、RESTEasy等JAX-RS实现;而@RequestMapping、@GetMapping是Spring Web的原生注解,两套体系完全独立,出现404是以下配置不匹配导致的:
- 类没有被Spring扫描到:如果你的项目之前是通过Jersey的ResourceConfig扫描带
@Path的类,换成Spring注解后,要保证CommonService在Spring的组件扫描范围内:要么把Controller类放在启动类所在包的同级/子包下,要么在启动类上加@ComponentScan(basePackages = "你的Controller所在包路径")手动指定扫描范围。 - 请求路径不匹配:类上
@RequestMapping("sample")和方法上@GetMapping("/s1")拼接的完整路径是/sample/s1,要确认Postman请求的路径、大小写完全匹配,不要多加或者漏写斜杠。如果你的项目配置了全局上下文路径(比如application.properties里配置了server.servlet.context-path=/demo),请求路径要改为/demo/sample/s1。 - 依赖/框架冲突:如果是Spring Boot项目,首先要确保已经引入
spring-boot-starter-web依赖;其次要移除之前JAX-RS相关的依赖、配置类,避免Jersey和Spring MVC两套web框架冲突,导致Spring的DispatcherServlet没有接管请求。
验证可用的参考配置
- Spring Web依赖(Maven示例)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
- Controller代码
import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Map; @RestController @RequestMapping("/sample") public class CommonService { @GetMapping(value = "/s1", produces = MediaType.APPLICATION_JSON) public Object get() { return Map.of("status", "ok", "data", "测试返回内容"); } }
- 启动类放在Controller的上级包路径下,启动项目后请求
GET http://{ip}:{port}/sample/s1即可正常拿到返回结果。
内容的提问来源于stack exchange,提问作者João Rodrigues
相关产品推荐
相关产品推荐

