beans.xml配置文件內容以下:java
<?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內容以下:mysql
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring jdbc.username=root jdbc.password=****
運行時報ClassNotFoundException: com.mysql.jdbc.Driver異常,mysql的驅動包明明是加進去的。更關鍵的一點是不使用佔位符,即以下:spring
<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>
這樣運行是正常的。後來發現異常 信息裏有這麼一句話sql
at org.apache.commons.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1420)apache
我在想有多是url
commons.dbcp.BasicDataSource
這個類沒法加載mysql驅動的問題。通過好長時間的查找,發現改爲spa
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
即正常。至此,大功告成!
code