Spring 整合mybatis时遇到的问题

来源:互联网 发布:淘宝店铺怎么关闭贷款 编辑:程序博客网 时间:2024/05/16 23:54

mybatis最喜欢用的就是它的动态代理了。原先做的普通java工程都是用一个工具类来保持mybatis的sqlSessionFactory,初始化后,便能不断从这里获取session。但现在要做一个WEB应用,使用到了struts2+spring+mybaits,这样,sqlSessionFactory就得由spring来注入,前面说了我就是要用mybatis的动态代理,因此我不写dao的实现类。

先看spring的applicationContext.xml的部分配置

<!-- 数据源属性配置方法: 导入资源文件 -->   <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">     <property name="locations">    <list>     <value>classpath:c3p0.properties</value>     </list>     </property>  </bean><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"><property name="driverClass" value="${c3p0.driverClass}"/>     <property name="jdbcUrl" value="${c3p0.jdbcUrl}"/>     <property name="user" value="${c3p0.user}"/>     <property name="password" value="${c3p0.password}"/>     <property name="minPoolSize">    <value type="long">${c3p0.minPoolSize}</value>    </property>     <property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>     <property name="initialPoolSize" value="${c3p0.initialPoolSize}"/> </bean><!-- Spring 管理MyBatis配置 多数据库支持-->      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">          <property name="dataSource" ref="dataSource" />        <property name="mapperLocations" value="classpath*:com/monitor/web/${c3p0.dbType}/mapper/*.xml" />      </bean>     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactory" ref="sqlSessionFactory"></property><property name="basePackage" value="com.monitor.web.dao"></property> </bean>


Spring管理Mybatis的部分:

mapperLocations指定你的SQL映射文件位置,也就是写SQL的xml文件的位置。

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="sqlSessionFactory" ref="sqlSessionFactory"></property><property name="basePackage" value="com.monitor.web.dao"></property> </bean>


这一部分,则是动态注入的部分,可参见http://thoughtfly.iteye.com/blog/1485993,我用的是扫描dao接口所在的包,实现注入

但是,上天不折腾折腾你是不会让你跑起来的,启动的时候容器报错:不能把String ${c3p0.minPollSize}转化为一个int类型,好吧,很明显这是没有把属性文件的值给替换掉,而是把我们数据源设置中的${}直接当字符串用了,蹊跷了好长时间,读取属性的部分没有问题啊。查了半天,终于查到点沾边的,看这个链接

http://www.oschina.net/question/188964_32305 

照着把<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>这句去掉,仍然不行。

 

好吧,问了问同学,他给我换了种读属性文件的方法

<!-- 数据源属性配置方法: 导入资源文件    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">     <property name="locations">    <list>     <value>classpath:c3p0.properties</value>     </list>     </property>  </bean>-->    <!-- 数据源属性配置方法: 导入资源文件 -->  <context:property-placeholder location="classpath:c3p0.properties" />


居然没事了。。。 

最后推断一下原因吧,应该就是链接中所说的动态注入,某些bean提前初始化导致的。spring要加强支持啊!