You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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错误:
404错误截图

已尝试的解决方案

  • 添加@ComponentScan注解
  • 修改@ComponentScan的basePackages和basePackageClasses属性
  • 使用@Configuration和CommandLineRunner
  • 手动配置Bean
  • 将@RequestMapping替换为@GetMapping
  • 将主类RestdemoApplication直接定义为RestController(此方案可行)

内容的提问来源于stack exchange,提问作者William Sharlaag

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 01:24:28