IntelliJ中已添加JDBC驱动但服务器启动时提示驱动加载失败
Hey there! I get it—frustrating when IntelliJ recognizes your MySQL driver but the server throws a "driver not found" error. Let's break down the most common fixes for this issue:
1. Ensure the Driver is in the Runtime Classpath
IntelliJ adding the driver as a module dependency only covers compile-time recognition. The server needs it in the runtime classpath to load it when the app runs. Here's how to fix this:
- Web Projects (e.g., Tomcat): Manually copy the MySQL driver jar into your project's
WEB-INF/libdirectory. This guarantees the server picks it up during deployment. - Maven/Gradle Projects: Make sure your dependency scope is set to
runtime(or the defaultcompile, which includes runtime). Avoidprovidedscope unless your server already bundles the MySQL driver (rare case). For Maven, your pom.xml should include:<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> <!-- Use your driver's actual version --> <scope>runtime</scope> </dependency>
2. Fix IntelliJ's Artifact & Deployment Config
Sometimes IntelliJ doesn't automatically include the driver in the deployed artifact. Let's adjust that:
- Open
File > Project Structure > Artifacts. - Select your web application artifact (usually named like
your-project:war exploded). - Check if the MySQL driver jar is listed under
WEB-INF/lib. If missing, click the+button, selectLibrary Files, and add your MySQL driver dependency. - Save changes, then head to your Run/Debug Configuration for the server. Under the
Deploymenttab, confirm the updated artifact is selected.
3. Double-Check the Driver Class Name
If you're using MySQL 8.0 or newer, the driver class name changed from com.mysql.jdbc.Driver to com.mysql.cj.jdbc.Driver. Old class names won't work with newer drivers, so update your code:
Class.forName("com.mysql.cj.jdbc.Driver"); // Correct for MySQL 8.0+
(Side note: Starting from JDBC 4.0, you might not even need Class.forName()—DriverManager can auto-detect the driver if it's in the classpath, but keeping it doesn't hurt for compatibility.)
4. Try Server-Specific Classpath (If Using Standalone Server)
If you're using an external server (like a standalone Tomcat instance), you can place the driver jar directly into the server's lib directory (e.g., tomcat/lib). This makes it available to all apps deployed on that server, though it's less project-specific than adding it to WEB-INF/lib.
Give these steps a go—nine times out of ten, the issue is just the driver not being present in the runtime classpath the server uses.
内容的提问来源于stack exchange,提问作者Jochaim Fischbach

