Spring Boot中Post/Get请求未映射,返回404错误求助
解决Spring Boot Controller未映射导致的404问题
看了你的代码和启动日志,核心问题很明确:Spring容器根本没扫描到你的ControllerRest类,所以请求映射完全没被注册,自然返回404。我整理了几个关键修复步骤,帮你快速解决问题:
1. 简化主类的注解配置
你的TestApplication主类里手动加了一堆注解,但其实@SpringBootApplication已经包含了@ComponentScan(默认扫描主类所在包及其所有子包)、@EnableAutoConfiguration和@Configuration功能,手动指定扫描范围反而画蛇添足,限制了Spring的扫描能力。
修改后的主类代码:
package com.abc.nice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.support.SpringBootServletInitializer; @SpringBootApplication public class TestApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(TestApplication.class, args); } }
这样Spring会自动扫描com.abc.nice下的所有子包(包括controller、entity、repo),不用再手动指定范围。
2. 修复Controller中的注入错误
你的ControllerRest里有两个明显的低级错误:
- 试图用
@Autowired注入实体类Messages:实体类不是Spring管理的Bean,Spring找不到对应的实例,要是Controller被扫描到的话,启动直接就失败了。 MessagesRepository没加@Autowired:即使Controller被扫描到,调用方法时也会因为Repo为空报空指针异常。
修改后的Controller代码:
package com.abc.nice.controller; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.abc.nice.entity.Messages; import com.abc.nice.repo.MessagesRepository; @RestController public class ControllerRest { @Autowired private MessagesRepository msgRepo; // 添加@Autowired注入Repository @GetMapping({ "/StatusData" }) public List<Messages> index() { return this.msgRepo.findAll(); } @PostMapping(path = {"/postdata"}) public ResponseEntity<Messages> createBody(@RequestBody Map<String, String> body) { // 实体类直接new就行,不需要依赖注入 Messages msgDao = new Messages(); msgDao.setTemplate(body.get("template")); msgDao.setParameters(body.get("parameters")); msgDao.setHsm(body.get("hsm")); msgDao.setTo(body.get("to")); return new ResponseEntity<>(msgRepo.save(msgDao), HttpStatus.OK); } }
3. 验证修复结果
重启应用后,盯着启动日志看,如果出现以下内容,说明请求映射已经成功注册:
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/StatusData]}" onto public java.util.List<com.abc.nice.entity.Messages> com.abc.nice.controller.ControllerRest.index() s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/postdata],methods=[POST]}" onto public org.springframework.http.ResponseEntity<com.abc.nice.entity.Messages> com.abc.nice.controller.ControllerRest.createBody(java.util.Map<java.lang.String,java.lang.String>)
这时候再发送GET /StatusData或POST /postdata请求,就不会再返回404了。
内容的提问来源于stack exchange,提问作者enemyofnone
相关产品推荐
相关产品推荐

