使用Postman调用SpringBoot REST接口时出现404错误求助
解决Postman调用SpringBoot REST接口返回404的问题
嘿,看你贴的代码,问题出在注解的使用和Spring Boot的默认支持上,咱们一步步来搞定它:
1. 核心问题:JAX-RS注解不被Spring Boot默认识别
你的PatientService用了JAX-RS的@Path、@GET(这是Jersey这类JAX-RS框架的注解),但Spring Boot默认是基于Spring MVC的,它认的是@RestController、@GetMapping这类注解,根本识别不了JAX-RS的注解,所以自然找不到接口路径,返回404。
方案一:改用Spring MVC注解(推荐,更贴合Spring生态)
把代码改成Spring MVC的写法,这是最省心的方式:
调整PatientService接口(去掉JAX-RS注解):
public interface PatientService { List<Patient> getPatients(); }
修改PatientServiceImpl实现类:
@RestController // 标记这是一个REST控制器,替代原来的JAX-RS注解逻辑 @RequestMapping("/patientservice") // 对应原来的@Path("/patientservice") public class PatientServiceImpl implements PatientService { Map<Long, Patient> patients = new HashMap<>(); long currentId = 123; public PatientServiceImpl() { init(); } void init() { Patient patient = new Patient(); patient.setId(currentId); patient.setName("John"); patients.put(patient.getId(), patient); } @Override @GetMapping("/patients") // 对应原来的@Path("/patients") + @GET public List<Patient> getPatients() { return new ArrayList<>(patients.values()); // 把Map里的值转成List返回 } }
改完之后启动应用,用Postman访问http://localhost:8080/patientservice/patients(如果改了端口就换成你的端口),应该就能拿到数据了。
方案二:继续用JAX-RS(需要额外配置)
如果你非要用JAX-RS的注解,那得给Spring Boot加上Jersey的支持:
第一步:添加Jersey依赖(Maven为例)
在pom.xml里加这个依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jersey</artifactId> </dependency>
第二步:创建Jersey配置类
注册你的服务实现类,让Jersey能找到它:
import org.glassfish.jersey.server.ResourceConfig; import org.springframework.context.annotation.Configuration; @Configuration public class JerseyConfig extends ResourceConfig { public JerseyConfig() { register(PatientServiceImpl.class); // 把你的服务类注册进去 } }
你的PatientServiceImpl已经有@Service注解,这一步没问题。之后启动应用,同样访问http://localhost:8080/patientservice/patients就能正常调用了。
额外排查点
- 检查启动类包路径:Spring Boot启动类的包要覆盖你的服务类所在包,比如启动类在
com.example.app,服务类得在com.example.app.service这种子包下,不然Spring扫不到你的服务。 - 确认Postman请求方法:一定要选GET,别选错成POST/PUT之类的。
- 核对端口号:如果application.properties里改了
server.port,访问时要对应改端口。
内容的提问来源于stack exchange,提问作者Cosmin Plesa
相关产品推荐
相关产品推荐

