ClassNotFoundException: com.mysql.jdbc.Driver

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"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    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
        http://www.springframework.org/schema/aop   
   	http://www.springframework.org/schema/aop/spring-aop.xsd">
        
        <context:property-placeholder location="classpath:jdbc.properties" /> 
     
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 
    <property name="driverClassName" value="${jdbc.driverClassName}"/> 
    <property name="url" value="${jdbc.url}"/> 
    <property name="username" value="${jdbc.username}"/> 
    <property name="password" value="${jdbc.password}"/>
  </bean> 
<bean id="userDao" class="dao.impl.UserDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>

<bean id="userInterceptor" class="aop.UserInterceptor"></bean>
<bean id="userService" class="service.UserService">
<property name="userDao" ref="userDao"></property>
</bean>



</beans>

src下新建jdbc.properties内容如下:

jdbc.driverClassName=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql://localhost:3306/spring 
jdbc.username=root 
jdbc.password=****

运行时报ClassNotFoundException: com.mysql.jdbc.Driver异常,mysql的驱动包明明是加进去的。更关键的一点是不使用占位符,即如下:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/> 
	     <property name="url" value="jdbc:mysql://localhost:3306/spring"/> 
	     <property name="username" value="root"/> 
	     <property name="password" value="19870509"/> 
  </bean>

这样运行是正常的。后来发现异常 信息里有这么一句话

at org.apache.commons.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1420)

我在想有可能是

commons.dbcp.BasicDataSource

这个类无法加载mysql驱动的问题。经过好长时间的查找,发现改成

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

即正常。至此,大功告成!

你可能感兴趣的:(ClassNotFoundException: com.mysql.jdbc.Driver)