spring+mybatis使用MapperScannerConfigurer引起的PropertyPlaceholderConfigurer无效问题处理方法

来源:互联网 发布:人工智能答案 编辑:程序博客网 时间:2024/04/29 23:21

问题描述:

    在spring里使用org.mybatis.spring.mapper.MapperScannerConfigurer 进行自动扫描的时候,设置了sqlSessionFactory 的话,他会优先于PropertyPlaceholderConfigurer执行,从而导致PropertyPlaceholderConfigurer失效,这时在xml中用${url}、${username}、${password}等这样之类的表达式,将无法获取到properties文件里的内容。

处理方法:

<!-- 配置mybatis --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="configLocation" value="classpath:mybatis-config.xml"></property><!-- mapper扫描 --><property name="mapperLocations" value="classpath*:com/xx/**/mapper/*Mapper.xml" /></bean><!-- 映射Mapper文件 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.xx.**.dao"></property><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property></bean>

修改为:

<!-- 配置mybatis --><bean id="mybatisSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="configLocation" value="classpath:mybatis-config.xml"></property><!-- mapper扫描 --><property name="mapperLocations" value="classpath*:com/xx/**/mapper/*Mapper.xml" /></bean><!-- 映射Mapper文件 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.xx.**.dao"></property><property name="sqlSessionFactoryBeanName" value="mybatisSqlSessionFactory"></property></bean>

问题分析:

           使用sqlSessionFactoryBeanName注入,不会立即初始化sqlSessionFactory, 所以不会引发提前初始化问题,同时还应注意在配置org.mybatis.spring.SqlSessionFactoryBean这个Bean时,id不能为sqlSessionFactory,如果为这样的话会导致MapperScannerConigurer在bean定义加载时,加载PropertyPlaceholderConfigurer还没来得及替换定义中的变量

0 0
原创粉丝点击