spring 和mybatis整合时 使用context:property-placeholder载不进属性 还报org.springframework.beans.factory.BeanCrea

在spring核心配置文件(applicationContext.xml)中配置




























问题:在spring 和mybatis组合时 使用该配置方式会报异常

异常为:org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.mybatis.spring.mapper.MapperScannerConfigurer#0' defined inclass path resource [spring/applicationContext-dao.xml]: Cannot resolve reference to bean 'sqlSessionFactoryBean' while setting bean property'sqlSessionFactoryBeanName'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name'sqlSessionFactoryBean' defined in class path resource [spring/applicationContext-dao.xml]: Cannot resolve reference to bean 'dataSource' while setting beanproperty 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined inclass path resource [spring/applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failedto convert property value of type 'java.lang.String' to required type 'int' for property 'maxActive'; nested exception is java.lang.NumberFormatException: For inputstring: "${jdbc.maxActive}"

问题分析

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

解决方法: 

改用sqlSessionFactoryBeanName注入就没有问题(不要使用sqlSessionFactory属性注入,使用sqlSessionFactoryBeanName注入),因为这时不会立即初始化sqlSessionFactory,传入的只是名字(即:将 ref="sqlSessionFactoryBean" 配置改成 value="sqlSessionFactoryBean"),非bean,所以不会引发提前初始化问题。
代码实现:


























你可能感兴趣的:(ssm整合)