问题: 写了一个新的 dao 接口, 进行单元测试时提示:
Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'maxActive'; nested exception is java.lang.NumberFormatException: For input string: "${maxActive}"
原配置 datasource 时使用了占位符, 该提示是在解析占位符 ${maxActive} 时未找到对应的属性.
单元测试加载 properties 使用 @PropertySource(value = {"classpath*:jdbc.properties"}) 注解加载配置文件.
在确认自己 properties 文件路径是正确的且存在该属性值后, 在网上找到相应的资料如 https://my.oschina.net/u/1455908/blog/215953 说的是在配置 mybatis 的 MapperScannerConigurer 时会优先于 @PropertySource 注解解析占位符, 由于占位符未进行解析, 直接使用了 "${maxActive}" 了该字符串作为该配置项的值. 也就是报错所说的 "${maxActive}" 这个字符串无法转化成对应的 int 数值.
解决问题
将配置文件的加载由原先使用注解 @PropertySource(value = {"classpath*:jdbc.properties"}) 改成如下:
- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="locations">
- <list>
- <value>classpath:jdbc.properties</value>
- </list>
- </property>
- <property name="ignoreUnresolvablePlaceholders" value="true"></property>
- </bean>
原先 MapperScannerConfigurer 的配置没有做修改, 如下:
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <property name="basePackage" value="com.**.dao,com.**.mapper,com.**.test.**.mapper" />
- <!-- 网上说这个 name 属性值要配置成这个 sqlSessionFactoryBeanName 名字, 我恰好配的就是这个, 所以我这里不需要改 -->
- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
- </bean>
这样该问题解决. 但疑问依然存在, 为何 @PropertySource 这个注解没有 ignoreUnresolvablePlaceholders 这个属性可以进行配置, 并且用 xml 的方式又能正确解析.
来源: http://www.bubuko.com/infodetail-3289697.html