问题描述:
这两天自己配置SPring+MyBatis遇到了个问题,搞了一天才搞定。就是PropertyPlaceholderConfigurer加载配置之后在DatasSource中的使用无效的问题。
以下是配置
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:properties/database.properties</value>
</list>
</property>
<property name="fileEncoding" value="utf-8"></property>
</bean>
<!-- 数据源1 -->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<!-- 数据库基本信息配置 -->
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxIdle" value="${jdbc.maxIdle}"/>
<property name="minIdle" value="${jdbc.minIdle}"/>
<property name="initialSize" value="${jdbc.initialSize}"/>
<property name="timeBetweenEvictionRunsMillis"
value="60000"/>
<property name="poolPreparedStatements" value="true"/>
<property name="maxOpenPreparedStatements" value="50"/>
<property name="removeAbandonedTimeout" value="180"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="mapperLocations" value="classpath:com/lubby/dao/*.xml"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.lubby.dao"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
思考方向:
1.在思考的过程中,想考虑了是不是Spring版本的问题,所以试了好几个版本,最后结果都是一样,PropertyPlaceholderConfigurer加载的配置依旧无效。
2.然后思考是不是数据源有问题,然后从c3p0数据源换成了dbcp2数据源。结果依然是PropertyPlaceholderConfigurer加载的配置无效。
真正原因:
MapperScannerConfigurer中如果通过SqlSessionFactory注入进去会导致DataSource提前实例化,PropertyPlaceholderConfigurer在其之后实例化,导致取到配置文件中的值。其实仔细看setSqlSessionFactory(SqlSessionFactory sqlSessionFactory)中已经注释了@Deprecated,
@deprecated Use {@link #setSqlSessionFactoryBeanName(String)} instead.
解决办法:
使用sqlSessionFactoryBeanName,这样只是传进去一个String,会在PropertyPlaceholderConfigurer工作完成之后实例化DataSource。
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.lubby.dao"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
来源:oschina
链接:https://my.oschina.net/u/2250599/blog/540664