创建bean时出错...无法加载JDBC驱动程序类[oracle.jdbc.driver.OracleDriver]

sam*_*ira 4 java spring jdbc

我编写了在Spring上使用JDBC运行查询的代码,但是我得到了一个例外(见下文)

这是我的context.xml

 <bean id="dataSource" 
       class="org.springframework.jdbc.datasource.DriverManagerDataSource">
   <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
   <property name="url" value="jdbc:oracle:thin:@Mohsen-PC:1521:mydb"/>
   <property name="username" value="system"/>
   <property name="password" value="123"/>    
 </bean>

 <bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler">
   <property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/>
 </bean>

 <bean id="nativeJdbcExtractor" 
     class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor"/>

 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
   <property name="dataSource" ref="dataSource"/>
 </bean>
</beans>
Run Code Online (Sandbox Code Playgroud)

main.java

import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

class Main {

  public static void main(String args[]) throws Exception {

    ApplicationContext ac = new ClassPathXmlApplicationContext("context.xml");

    DataSource dataSource = (DataSource) ac.getBean("dataSource");

    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

    System.out.println(jdbcTemplate.queryForList("select EMPLOYEE_ID from EMPLOYEE", 
                                                  Long.class));
  }
}
Run Code Online (Sandbox Code Playgroud)

我看到的例外是:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: 
  Error creating bean with name 'dataSource' defined in class path resource [context.xml]: 
  Error setting property values; nested exception is 
  org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
  PropertyAccessException 1: org.springframework.beans.MethodInvocationException: 
  Property 'driverClassName' threw exception; nested exception is 
  java.lang.IllegalStateException: Could not load JDBC driver class 
  [oracle.jdbc.driver.OracleDriver] at 
  org.springframework.beans.factory.support.
                             AbstractAutowireCapableBeanFactory.applyPropertyValues(
                                                AbstractAutowireCapableBeanFactory.java:1396)
Run Code Online (Sandbox Code Playgroud)

编辑:剪切堆栈跟踪的剩余部分,因为上述异常足以说明问题.

这里出了什么问题?

Aru*_*hny 12

看起来你在类路径中缺少oracle jdbc驱动程序.请从此路径下载jar文件并将其添加到类路径中.

EDITED
Spring jdbc是一个模板层,它在原始jdbc层之上工作.它只是为我们提供了一些实用程序方法,使数据库访问更容易.该层内部需要jdbc层才能工作,因此必须包含要连接到该数据库驱动程序的每个数据库,在您需要包含Oracle驱动程序的情况下.

  • @sami不是那个.您需要Oracle的JDBC驱动程序JAR文件. (2认同)