Spring Boot控制器接口404:Postman无法访问Controller方法
Spring Boot控制器接口404问题解决
问题场景
Spring Boot项目中,通过Postman访问http://localhost:8080/king/all时返回404错误,但将接口方法移到主类中可正常访问,仅控制器类与主类包路径不同。
控制器代码
package com.team4.controllers; @RestController @RequestMapping("/king") public class KingController { @Autowired private KingRepository kingRepo; @GetMapping("/all") public List<King> list() { return kingRepo.findAll(); } @GetMapping("/{id}") public King get(@PathVariable Long id) { return kingRepo.getReferenceById(id); } @PostMapping("/add") public King create(@RequestBody final King king) { return kingRepo.saveAndFlush(king); } @PutMapping("/update") public King update(@RequestBody final King king) { return kingRepo.saveAndFlush(king); } @DeleteMapping("/delete/{id}") public void delete(@PathVariable Long id) { kingRepo.deleteById(id); } }
返回的404错误信息
{ "timestamp": "2023-03-07T01:17:43.041+00:00", "status": 404, "error": "Not Found", "message": "No message available", "path": "/king/all" }
主类代码
package com.team4; @SpringBootApplication @EntityScan( basePackages = {"com.team4.model.*"} ) @EnableJpaRepositories("com.team4.model.*") @ComponentScan( basePackages = { "com.team4.model.*", "com.team4.controllers.*" } ) public class BoardGameProjectApplication { public static void main(String[] args) { SpringApplication.run(BoardGameProjectApplication.class, args); } }
问题原因
问题出在扫描路径的配置上:
@ComponentScan中配置的"com.team4.controllers.*"会扫描该包下的子包,而非包本身的类,导致Spring无法识别KingController组件。- 同理,
@EntityScan和@EnableJpaRepositories配置的"com.team4.model.*"也是错误的,该写法不会扫描com.team4.model包本身的实体类和Repository。
解决方案
有两种可行的解决方式:
方式一:修正扫描路径
修改主类的注解配置,将扫描路径改为包本身:
package com.team4; @SpringBootApplication @EntityScan(basePackages = {"com.team4.model"}) @EnableJpaRepositories("com.team4.model") @ComponentScan(basePackages = {"com.team4.model", "com.team4.controllers"}) public class BoardGameProjectApplication { public static void main(String[] args) { SpringApplication.run(BoardGameProjectApplication.class, args); } }
方式二:移除手动扫描配置(推荐)
@SpringBootApplication注解默认包含@ComponentScan、@EnableAutoConfiguration和@Configuration,且默认会扫描主类所在包及其所有子包。你的主类位于com.team4,控制器在com.team4.controllers、实体和Repository在com.team4.model,均为主类包的子包,完全不需要手动配置扫描路径。简化后的主类代码如下:
package com.team4; @SpringBootApplication public class BoardGameProjectApplication { public static void main(String[] args) { SpringApplication.run(BoardGameProjectApplication.class, args); } }
内容的提问来源于stack exchange,提问作者Nathan
相关产品推荐
相关产品推荐

