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

Spring Boot无法扫描子包及同包类,接口返回404求助

Spring Boot REST接口404异常问题

我用Spring Boot编写简单REST接口时遇到以下问题:

  • 只有标注@SpringBootApplication的主类内部定义的接口能正常工作,请求返回正确结果
  • 无论把接口放在主包的子包下,还是直接放在主包目录中,请求均返回404
  • 尝试过手动添加@ComponentScan(basePackages = "com.gowtham")指定扫描范围,也将接口类移到主包下,都无法解决问题
  • 但将同一项目导入其他电脑,所有接口都能正常运行

主类代码(内部接口可正常响应)

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@ComponentScan(basePackages = "com.gowtham")
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    
    @RestController
    public class controller {
        @GetMapping("/greet")
        public String hello() {
            return "HELLO";
        }
    }
}

其中/greet接口可正常返回结果。

子包下的接口代码(请求返回404)

该接口位于主包下的.controller子包中:

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ccc {
    
    @GetMapping("/gg")
    public String hello() {
        return "HELLO";
    }
}

/gg接口无法正常工作,请求返回404。

项目包结构

包结构截图

内容的提问来源于stack exchange,提问作者gowtham-s001

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 10:52:19