Spring构建REST API遇404错误,RestController未自动识别求助
Spring Boot REST API 404问题:RestController疑似未被自动识别
我正在用Spring构建REST API,但一个简单示例运行失败,查了多篇文章、试了多种方法都没解决,推测问题出在RestController未被自动识别。
项目结构

主类代码(RestdemoApplication)
package rest.restdemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class RestdemoApplication { public static void main(String[] args) { SpringApplication.run(RestdemoApplication.class, args); } }
RestController代码(RestingController)
package rest.restdemo; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class RestingController { @RequestMapping("/hello") String hello() { return "Hello"; } }
访问结果
请求/hello时返回404错误:
已尝试的解决方案
- 添加
@ComponentScan注解 - 修改
@ComponentScan的basePackages和basePackageClasses属性 - 使用
@Configuration和CommandLineRunner - 手动配置Bean
- 将
@RequestMapping替换为@GetMapping - 将主类RestdemoApplication直接定义为RestController(此方案可行)
内容的提问来源于stack exchange,提问作者William Sharlaag
相关产品推荐
相关产品推荐

