I am learning Spring Framework and trying to inject properties from the .properties file.
This is my .properties file
sprint.datasource.username=hamnghi
sprint.datasource.password=hamnghi
sprint.datasource.url=jdbc:h2:~/test;
sprint.datasource.driver=org.h2.Driver;
When I tried to pass the driver
field into the Class.forName(drive)
, the program could not connect to the
database and threw a java.lang.ClassNotFoundException: org/h2/Driver;
but it printed the driver
variable as "org.h2.Driver" to the console just fine.
My console screenshot
I also ran the program with Class.forName("org.h2.Driver")
, and it ran fine; however, when I replaced it with the driver
, it didn't work
This is my class.
package H2Database.db_connection;
import H2Database.functionality.Logging;
import org.springframework.beans.factory.annotation.Value;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Logger;
public class H2Connection {
private final static Logger logger = Logging.getLogger();
@Value("${sprint.datasource.url}")
private String url;
@Value("${sprint.datasource.username}")
private String username;
@Value("${sprint.datasource.password}")
private String password;
@Value("${sprint.datasource.driver}")
private String driver;
public Connection open(){
try {
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
@Override
public String toString() {
return "H2Connection{" +
"url='" + url + '\'' +
", username='" + username + '\'' +
", driver='" + driver + '\'' +
'}';
}
}
EDITED
You have trailing ;
in your config. remove it
The exception means the specific class is not found in the classpath.
You need to add the dependency contains the corresponding implemenation for h2:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>