引入JDBC API依赖后Spring Boot的RequestMapping无法正常工作
问题:Spring Boot REST API访问localhost:8080无返回内容
我正在学习Spring Boot,想要创建一个从MySQL数据库读取数据的REST API。已经在项目中引入Spring Web依赖与JDBC API依赖,但在浏览器中访问localhost:8080时没有任何内容返回。
控制器代码
@RestController public class MainController { @RequestMapping(path = "/") public String getGreeting(){ return "Hi there"; } }
pom.xml配置
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>live-elevation-backend</artifactId> <version>0.0.1-SNAPSHOT</version> <name>live-elevation-backend</name> <description>Backend layer for rack elevation</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
排查与解决方法
- 控制器未被Spring扫描:检查
MainController所在包是否在Spring Boot主启动类的同级或子包下。Spring Boot默认只扫描主启动类所在包及其子包的组件,若控制器在其他包,需在主启动类添加@ComponentScan(basePackages = "你的控制器包路径")。 - 缺失主启动类:确认项目存在标注
@SpringBootApplication的主启动类,示例如下:
@SpringBootApplication public class LiveElevationBackendApplication { public static void main(String[] args) { SpringApplication.run(LiveElevationBackendApplication.class, args); } }
- 端口被占用:检查8080端口是否被其他程序占用,可修改
application.properties更换端口,添加server.port=8081后重启项目再访问。 - 项目启动异常:查看控制台日志,确认启动过程无报错。因引入JDBC依赖但未配置MySQL连接,可能导致启动失败,可先在
application.properties添加基础配置:
spring.datasource.url=jdbc:mysql://localhost:3306/你的数据库名?useSSL=false&serverTimezone=UTC spring.datasource.username=你的数据库用户名 spring.datasource.password=你的数据库密码 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- 请求路径优化:可将
@RequestMapping(path = "/")替换为@GetMapping("/"),语义更明确,功能一致。
内容的提问来源于stack exchange,提问作者Asem Shaath
相关产品推荐
相关产品推荐

