Spring及Mybatis整合占位符解析失敗問題解決
問題:寫了一個新的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的方式又能正確解析。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
