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

Spring Boot Get API接口返回404 Not Found问题求助

解决Spring Boot GET API 404 Not Found问题

咱们来一步步排查你遇到的404问题,主要有几个关键问题需要修正:

1. Controller方法访问权限错误

你的userInfo()方法用了private修饰,Spring MVC无法识别并映射私有方法作为API接口。必须把方法改成public,这样Spring才能正确注册这个GET请求的映射。

修改后的ProfileController核心代码:

@RestController
public class ProfileController {
    @GetMapping(path = "/profile")
    // 把private改成public,同时调整返回类型为Profile
    public ResponseEntity<Profile> userInfo(){ 
        // ... 逻辑部分
    }
}

2. Profile类的Spring管理问题

你在Controller里用@Autowired注入Profile,但Profile类上没有任何Spring组件注解(比如@Component),也没通过@Bean配置到容器中,这会导致Spring无法找到该Bean,轻则运行时出现空指针,重则启动报错。

更合理的做法是:既然Profile是数据传输对象(DTO),无需让Spring管理,直接在方法内实例化即可:

@RestController
public class ProfileController {
    @GetMapping(path = "/profile")
    public ResponseEntity<Profile> userInfo(){
        // 直接new实例,避免不必要的Spring注入
        Profile profile = new Profile(); 
        profile.setSlackUsername("Ajava");
        profile.setBackend(true);
        profile.setAge(0); // 注意00会被解析为八进制数,直接写0更规范
        profile.setBio("My name is Anakhe Ajayi, I'm learning Java everyday and I love Jesus");
        return ResponseEntity.ok(profile);
    }
}

3. @ComponentScan路径格式错误

你的主启动类里@ComponentScan用了斜杠/分隔包路径,这是错误的,Java包路径应该用点.分隔。而且默认情况下,@SpringBootApplication已经会扫描主类所在包及其所有子包,只要Controller在这个范围内,完全可以去掉额外的@ComponentScan配置。

修改后的主启动类:

@SpringBootApplication
// 如果Controller在主类的子包下,这行ComponentScan可以直接删除
// @ComponentScan("com.ajavacode.HNGBackendStage1.api.profile")
public class HngBackendStage1Application {
    public static void main(String[] args) {
        SpringApplication.run(HngBackendStage1Application.class, args);
    }
}

如果Controller不在默认扫描路径下,再把@ComponentScan的路径改成com.ajavacode.HNGBackendStage1.api.profile这种点分隔格式。

4. 返回值格式优化

原来的方法返回ResponseEntity<String>,用profile.toString()得到的是Java对象的字符串表示,不是标准JSON。改成返回ResponseEntity<Profile>后,Spring会自动用Jackson将对象序列化为JSON,这才符合REST API的规范。

把这些修改完成后,重启Spring Boot应用,访问http://localhost:8080/profile(如果改了端口就用对应端口),应该就能正常返回你的Profile数据了。


内容的提问来源于stack exchange,提问作者Plus Ultra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 12:57:48