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

Spring Boot本地应用访问报404错误,启动日志无异常

解决你的Spring Boot应用404问题

嘿,我看了你的问题和代码,首先发现一个最可能的问题:你访问的是localhost(也就是http://localhost:8080/),但你的控制器方法明确映射到了/test路径,所以正确的访问地址应该是 http://localhost:8080/test,这大概率就是导致404的直接原因!

我们再逐一确认其他配置是否没问题:

1. 组件扫描配置

你的主类TestApplication和控制器TestController都在com.test.controller包下,@SpringBootApplication注解已经包含了@ComponentScan功能,默认会扫描主类所在包及其子包的所有Spring组件,所以你的控制器肯定会被正确扫描到,这部分完全没问题。

2. 控制器注解检查

你的控制器类用了@RestController,这个注解已经整合了@Controller和@ResponseBody,所以哪怕你导入了@Controller但没使用,也不会有影响。方法上的@RequestMapping配置也很规范,指定了GET请求和/test路径,没有问题。

3. 关于SpringBootServletInitializer的小误区

因为你是打包成jar包,用Spring Boot内置的Tomcat启动,所以完全不需要让主类继承SpringBootServletInitializer——这个类是给打包成war包、部署到外部Servlet容器(比如独立Tomcat服务器)时用的,现在你可以去掉这个继承,避免冗余配置。

你的主类代码(无问题)

package com.test.controller;
@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
}

你的控制器代码(无问题)

package com.test.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@RestController
public class TestController {
    public final Logger logger = LoggerFactory.getLogger(TestController.class);
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test() {
        logger.info("This is a test message to check if logback is working");
        return "Hello World";
    }
}

额外排查建议(如果还是404)

如果访问http://localhost:8080/test依然报错,可以检查:

  • 启动日志里有没有类似Mapped "{[/test],methods=[GET]}"的日志,这条日志说明Spring已经正确映射了你的接口。如果没有,说明控制器没被扫描到,这时候可以手动指定扫描范围:@SpringBootApplication(scanBasePackages = "com.test")(不过你的情况应该不需要)。
  • 确认应用确实在8080端口运行,从你的日志来看Tomcat started on port(s): 8080 (http),端口是对的。

赶紧试试访问http://localhost:8080/test,应该就能看到你想要的"Hello World"了!

内容的提问来源于stack exchange,提问作者ANKIT SRIVASTAVA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:21:01