Spring Boot+MySQL REST接口404问题:新增员工接口无法访问
Spring Boot POST接口返回404 Not Found问题排查与解决
问题描述
开发基于Spring Boot和MySQL的REST应用时,调用POST /api/employees接口添加员工记录,预期返回新增的记录,但Postman返回404错误:
{"status":404,"error":"Not Found","path":"/api/employees"}
相关代码
EmployeeController.java
package com.controller; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.service.EmployeeService; import com.model.Employee; @RestController @RequestMapping("/api") public class EmployeeController { private EmployeeService employeeservice; public EmployeeController(EmployeeService employeeservice) { super(); this.employeeservice = employeeservice; } //build create Employee REST API @PostMapping("/employees") public ResponseEntity<Employee> saveEmployee(@RequestBody Employee employee) { return new ResponseEntity<>(employeeservice.saveEmployee(employee), HttpStatus.CREATED); } }
RestapimysqlApplication.java
package com; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; @EnableJpaRepositories( basePackages = {"com.model"}) @SpringBootApplication(scanBasePackages = {"service.impl"}) public class RestapimysqlApplication { public static void main(String[] args) { SpringApplication.run(RestapimysqlApplication.class, args); } }
问题原因
- 组件扫描范围错误:
@SpringBootApplication的scanBasePackages仅指定了service.impl,导致com.controller包未被Spring扫描,Controller类无法被识别,对应的路由/api/employees自然不存在。 - JPA Repository扫描包错误:
@EnableJpaRepositories指定的basePackages是com.model,但JPA Repository接口通常放在单独的包(如com.repository),此配置会导致Spring无法找到Repository实例,后续Service层调用也会出错。
解决方案
修改启动类配置
调整@SpringBootApplication和@EnableJpaRepositories的包扫描范围:
package com; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; // 指向JPA Repository接口所在的包,示例为com.repository @EnableJpaRepositories(basePackages = {"com.repository"}) // 去掉scanBasePackages,默认扫描启动类所在的com包及其所有子包 @SpringBootApplication public class RestapimysqlApplication { public static void main(String[] args) { SpringApplication.run(RestapimysqlApplication.class, args); } }
补充说明
- 若需显式指定扫描包,可将
@SpringBootApplication改为:@SpringBootApplication(scanBasePackages = {"com.controller", "com.service", "com.service.impl", "com.model"}) @SpringBootApplication默认会扫描启动类所在包(com)及其所有子包,因此只要Controller、Service等组件放在com的子包下,无需额外配置scanBasePackages,更不易出错。
内容的提问来源于stack exchange,提问作者Hossam Maghrabi
相关产品推荐
相关产品推荐

