SpringBoot配置@RequestMapping的POST接口访问报404如何解决
问题根源
你把@RestController注解标注在了Controller接口上,Spring MVC默认不会识别接口上的控制器注解,也不会自动将接口的注解继承到实现类,因此Spring容器没有把你的路由接口识别为HTTP接口处理器,所以访问时报404。
解决步骤
- 第一步:删掉
RouteController接口上的@RestController注解,在实现类RouteControllerImpl上添加@RestController注解
Spring会识别实现类上的控制器注解,同时自动继承接口上定义的@RequestMapping、参数校验、Swagger注解等配置,无需重复编写。 - 第二步:确认实现类被Spring组件扫描覆盖
检查RouteControllerImpl所在的包路径,是否在启动类@SpringBootApplication默认的扫描范围(启动类所在包及其子包)内,如果不在,需要在启动类上添加扫描配置:@SpringBootApplication @ComponentScan(basePackages = "com.xxx.你的实现类所在包路径") public class ApplicationStart { public static void main(String[] args) { SpringApplication.run(ApplicationStart.class, args); } } - 第三步:校验请求配置是否匹配
你当前接口配置了consumes = "application/json",发请求时必须携带Content-Type: application/json请求头,且请求体为合法JSON格式;如果项目配置了全局上下文路径server.servlet.context-path,访问路径需要加上对应前缀。
修改后代码示例
接口代码
public interface RouteController { @ApiOperation(value = "Add a route details to adapter", nickname = "addroute", notes = "Add route details to the table and Send it to ATLAS", tags = { "route", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Successful Insertion into DB and Proceded for Transformation"), @ApiResponse(code = 405, message = "Invalid Input") }) @RequestMapping(value = "/route", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.POST) ResponseEntity<Void> createData( @ApiParam(value = "Route Array", required = true) @Valid @RequestBody RouteArray routeArray) ; }
实现类代码
@RestController public class RouteControllerImpl implements RouteController { @Autowired private RouteService routeService; @Override public ResponseEntity<Void> createData(@ApiParam(value = "Route Details", required = true) @Valid @RequestBody RouteArray routeArray) { return new ResponseEntity<Void>(routeService.transformRoute(routeArray)); } }
内容的提问来源于stack exchange,提问作者coldfusion_xxxx
相关产品推荐
相关产品推荐

