Eclipse下Spring Boot报错:Cannot load driver class: com.mysql.jdbc.Driver
Hey there! I remember hitting this exact error when I was starting out with Spring Boot and MySQL, so let's get this sorted for you. Here are the most common fixes to try:
1. Verify Your MySQL Connector Dependency is Correct
The biggest culprit here is usually a missing or mismatched MySQL JDBC driver dependency. Let's make sure you have the right one for your MySQL version:
If you're using MySQL 5.x
Your driver class com.mysql.jdbc.Driver is correct, but you need to add this dependency to your pom.xml (Maven) or build.gradle (Gradle):
Maven:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.49</version> <!-- Use the latest stable 5.x version --> </dependency>
Gradle:
implementation 'mysql:mysql-connector-java:5.1.49'
If you're using MySQL 8.x
MySQL 8.x changed the driver class name to com.mysql.cj.jdbc.Driver, and the dependency structure is slightly different. You'll need two changes:
- Update your
application.propertiesdriver class line to:spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver - Add the correct dependency:
Maven:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> <!-- Use the latest stable 8.x version --> </dependency>
Gradle:
implementation 'mysql:mysql-connector-java:8.0.33'
Also, for MySQL 8.x, you should add timezone parameters to your JDBC URL to avoid additional errors:
spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredatabase?useSSL=false&serverTimezone=UTC
2. Refresh Your Dependencies
Even if you added the dependency, sometimes your IDE or build tool doesn't pick it up right away:
- For Maven: Run
mvn clean installin your project root to rebuild and refresh dependencies. - For Gradle: Run
gradle clean buildor use the "Refresh Gradle Project" option in your IDE. - In IDEs like IntelliJ or Eclipse, you can also right-click your project and select "Maven/Gradle > Reload Project" to ensure the driver jar is downloaded and added to your classpath.
3. Double-Check Your Configuration Spelling
It sounds silly, but typos happen! Make sure your spring.datasource.driver-class-name line is spelled perfectly:
- No missing dots, correct capitalization (
com.mysql.jdbc.Driverorcom.mysql.cj.jdbc.Driverdepending on your version) - No extra spaces before or after the class name
4. Confirm the Driver Jar is in Your Classpath
If you're still stuck, check if the MySQL connector jar is actually present in your project's dependencies. In IntelliJ, you can go to File > Project Structure > Libraries to see if it's listed. If not, manually add it or re-run your build command to download it.
Once you've made these changes, restart your Spring Boot application and the error should be gone. Let me know if you hit any other snags!
内容的提问来源于stack exchange,提问作者Saakshi

