gpt4 book ai didi

带有 Eclipse 和 Tomcat 的 Java EE : Driver not found

转载 作者:行者123 更新时间:2023-11-29 06:04:57 25 4
gpt4 key购买 nike

我正在开发一个 Java EE 项目(配置如下),我遇到了一个似乎是常规异常的问题:java.lang.ClassNotFoundException: com.mysql.jdbc.Driver .

我正在使用 Eclipse、嵌入式 Tomcat 7 和 Maven,即使为测试找到了驱动程序,Tomcat 也找不到。

我搜索了一些答案 1 , 23但建议不清楚:建议改成mysql-connector-javaprovided ,并手动复制服务器中的依赖项(不清楚如何)。

但我不明白为什么我要排除部署依赖(范围provided)并手动添加它,这不是矛盾吗?

看完Maven documentation ,我觉得运行环境需要依赖项,因此 compile范围是最合适的。

正如您所看到的,我正在努力解决这些问题,所以我宁愿得到一个解释,也不愿得到一个神奇的修复。

配置:

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>

数据库属性:

  • URL = jdbc:mysql://127.0.0.1:3306/XXX-db?zeroDateTimeBehavior=convertToNull
  • USERBD = XXX
  • PASSWORDBD = XXX
  • DRIVER = com.mysql.jdbc.Driver

属性加载:

static {
try {

Properties databaseProperties = new Properties();
InputStream inputStream = DatabaseConnection.class.getClassLoader()
.getResourceAsStream(PROPERTIES_FILE);
if (inputStream != null) {
databaseProperties.load(inputStream);
} else {
throw new FileNotFoundException(
"property file '" + PROPERTIES_FILE + "' not found in the classpath");
}
Class.forName(databaseProperties.getProperty("DRIVER"));
USERBD = databaseProperties.getProperty("USERBD");
PASSWORDBD = databaseProperties.getProperty("PASSWORDBD");
URL = databaseProperties.getProperty("URL");
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}

最佳答案

Tomcat 7 JNDI docs给你答案:放在Tomcat的/lib文件夹下。

The JRE Memory Leak Prevention Listener that is included with Apache Tomcat solves this by triggering the drivers scan during Tomcat startup. This is enabled by default. It means that only libraries visible to the listener such as the ones in $CATALINA_BASE/lib will be scanned for database drivers. If you are considering disabling this feature, note that the scan would be triggered by the first web application that is using JDBC, leading to failures when this web application is reloaded and for other web applications that rely on this feature.

Thus, the web applications that have database drivers in their WEB-INF/lib directory cannot rely on the service provider mechanism and should register the drivers explicitly.

关于带有 Eclipse 和 Tomcat 的 Java EE : Driver not found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42352645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com