【发布时间】:2023-04-07 09:24:01
【问题描述】:
在练习 Spring 框架时,我希望我的 JDBC 连接在外部类上。但是,在我的 main 方法上创建对象并调用 .connectToDB() 方法时,我不断收到这种错误:
java.lang.ClassNotFoundException: "com.mysql.jdbc.Driver"
这是我的代码:
DBConnection.java(有依赖的类)
package com.jrs.annotation;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Value;
public class DBConnection {
@Value("${mysql.driver}")
private String driver;
@Value("${mysql.url}")
private String url;
@Value("${mysql.password}")
private String password;
@Value("${mysql.username}")
private String username;
public void displayConnection(){
System.out.println("Driver: " + this.driver + "\nURL: "+ this.url + "\nUsername" + this.username + "\nPassword" + this.password);
}
public void connectToDB() throws SQLException, ClassNotFoundException {
Class.forName(this.driver);
Connection con = DriverManager.getConnection(url, username, password);
System.out.println("Connection has been established");
}
}
Client.java(我的主方法类)
package com.jrs.annotation;
import java.sql.Connection;
import java.sql.DriverManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Client {
public static void main(String[] args) throws Exception {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
DBConnection con = context.getBean("dbconnection",DBConnection.class);
con.displayConnection();
con.connectToDB();
}
}
connection_details.properties(数据库连接的值)
mysql.driver = "com.mysql.jdbc.Driver"
mysql.url = "jdbc:mysql://127.0.0.1:3306/school"
mysql.username= "root"
mysql.password= ""
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<context:property-placeholder location="connection_details.properties" />
<bean id = "dbconnection" class = "com.jrs.annotation.DBConnection">
</bean>
</beans>
我尝试在我的 Main 方法上执行连接代码,并且 它正在工作。 当我将它放在外部类的方法上并在我的 main 上调用它时,我只得到了那种错误。有什么我错过的吗?
谢谢。
解决方案: 我已经发现了问题所在,connection_details.properties 上的值不需要单引号或双引号。谢谢你的想法。
connection_details.properties 的正确代码
mysql.driver = com.mysql.jdbc.Driver
mysql.url = jdbc:mysql://127.0.0.1:3306/school
mysql.username= root
mysql.password=
【问题讨论】:
-
能否请您显示不起作用的代码?而不是正在工作的那个
-
@AbhinabaChakraborty 列出的代码不起作用。措辞可能不是很清楚,但是 OP 尝试从 main 方法内部运行所有内容,并且有效。但是,当前代码使用 bean 和外部类,这不起作用。
-
是的,@Fullslack.dev,这正是我的问题。
-
@user3819290 首先,你检查过这些属性占位符是否有效吗?
-
@AbhinabaChakraborty,是的。我可以测试属性占位符是否正在通过
displayConnection()方法工作。就我而言,我可以获取值。