---
title: "java.lang.ClassNotFoundException: ${driverClass} 解决方案"
author: "明天会更浩"
date: "2014-10-31T20:06:48Z"
tags: []
categories: ["企业架构"]
slug: "java-lang-classnotfoundexception-driverclass"
draft: false
lastmod: "2014-10-31T20:06:48Z"
id: 2150814
url: "https://708990141.iteye.com/blog/2150814"
---

我的项目中用到了spring3.2.5+mybatis3.1.1+mybatis-spring1.2.1，我把数据库连接信息写在配置文件里，然后在spring配置文件中加上&lt;context:property-placeholder location="file:D:\\foxking\\taobao.properties" /&gt; 来引入，dataSource配置如下：

[![](http://static.oschina.net/uploads/space/2013/1128/114602_UepW_1157906.jpg)](http://static.oschina.net/uploads/space/2013/1128/114602_UepW_1157906.jpg)

 

    程序一运行就报：java.lang.ClassNotFoundException: ${driverClass} ............等一大堆错误，spring 配置检查了N多遍，没发现问题，让我很郁闷。于是不停的百度、Google，不停的改配置、测试，问题依然没有解决。后来终于找到了解决方法。

    先说一下问题的原因所在：

    在spring里使用org.mybatis.spring.mapper.MapperScannerConfigurer 进行自动扫描的时候，设置了sqlSessionFactory 的话，可能会导致PropertyPlaceholderConfigurer失效，也就是用${jdbc.username}这样之类的表达式，将无法获取到properties文件里的内容。 导致这一原因是因为，MapperScannerConigurer实际是在解析加载bean定义阶段的，这个时候要是设置sqlSessionFactory的话，会导致提前初始化一些类，这个时候，PropertyPlaceholderConfigurer还没来得及替换定义中的变量，导致把表达式当作字符串复制了。 但如果不设置sqlSessionFactory 属性的话，就必须要保证sessionFactory在spring中名称一定要是sqlSessionFactory ，否则就无法自动注入。又或者直接定义 MapperFactoryBean ，再或者放弃自动代理接口方式。 

    出问题的原因找到了，现在再找方法解决问题，方法如下：

&lt;bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"&gt;  

&lt;property name="basePackage" value="com.xxxx.dao.mapper" /&gt; 

&lt;property name="sqlSessionFactoryBeanName" value="sf1" /&gt;

 &lt;!-- &lt;property name="sqlSessionFactory" ref="sf1"&gt;&lt;/property&gt; --&gt;

 &lt;/bean&gt;

    改用sqlSessionFactoryBeanName注入就没有问题(不要使用sqlSessionFactory属性注入，使用sqlSessionFactoryBeanName注入)，因为这时不会立即初始化sqlSessionFactory,传入的只是名字，非bean，所以不会引发提前初始化问题。

    本文参考自[http://www.oschina.net/question/188964\_32305?sort=default&p=1#answers](http://www.oschina.net/question/188964_32305?sort=default&p=1#answers)