一、背景說明
新搭建了一個項目,框架使用的spring+spring Mvc+Mybatis ,數據庫使用的是MySql,項目可正常啓動,但是在功能中使用數據庫時就出現以下錯誤信息:
### Error updating database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create JDBC driver of class 'com.mysql.jdbc.Driver' for connect URL '${timer.bin.mysql.url}'
### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create JDBC driver of class 'com.mysql.jdbc.Driver' for connect URL '${timer.bin.mysql.url}'
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:76)
二、問題排查
首先想到的是Spring 的配置文件沒有加載,導致 ${timer.bin.mysql.url} 無法正常賦值導致問題的產生,於是嘗試了各種修改web.xml 、spring-mvc配置文件,調整spring 配置文件的加載順序,始終無法解決問題,詳細配置如下所示:
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:timer-test.properties</value>
</list>
</property>
<property name="fileEncoding">
<value>UTF-8</value>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="${timer.bin.mysql.url}"/>
<property name="username" value="${timer.bin.mysql.user.name}"/>
<property name="password" value="${timer.bin.mysql.user.pwd}"/>
<!--....-->
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.timer.bin.dao.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
在java代碼中直接使用spring的 @Value("${timer.bin.mysql.url}") 給屬性賦值,可以正常賦值使用,只有在dataSource 中無法進行正常賦值,始終提示錯誤 SQLNestedException: Cannot create JDBC driver of class 'com.mysql.jdbc.Driver' for connect URL '${timer.bin.mysql.url}'
三、解決方案
問題原因:由於定義 SqlSessionFactoryBean 這個bean時id名稱錯誤的命名爲 sqlSessionFactory ,最終導致問題產生
解決方案所示:修改 SqlSessionFactoryBean 這個bean 的id 名稱命名爲 timerSqlSessionFactory 或任意其他值,解決問題
<bean id="timerSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.timer.bin.dao.mapper"/>
<property name="sqlSessionFactoryBeanName" value="timerSqlSessionFactory"></property>
</bean>
根本原因:暫未得知,有待考察