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}時未找到對應(yīng)的屬性。
單元測試加載properties使用@PropertySource(value = {"classpath*:jdbc.properties"})注解加載配置文件。
在確認自己properties文件路徑是正確的且存在該屬性值后,在網(wǎng)上找到相應(yīng)的資料如https://my.oschina.net/u/1455908/blog/215953說的是在配置mybatis的MapperScannerConigurer時會優(yōu)先于@PropertySource注解解析占位符,由于占位符未進行解析,直接使用了“${maxActive}”了該字符串作為該配置項的值。也就是報錯所說的“${maxActive}”這個字符串無法轉(zhuǎn)化成對應(yīng)的int數(shù)值。
解決問題
將配置文件的加載由原先使用注解@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" /> <!--網(wǎng)上說這個name屬性值要配置成這個sqlSessionFactoryBeanName名字,我恰好配的就是這個,所以我這里不需要改--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean>
這樣該問題解決。但疑問依然存在,為何@PropertySource這個注解沒有ignoreUnresolvablePlaceholders這個屬性可以進行配置,并且用xml的方式又能正確解析。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
idea本地jar使用maven打包本地依賴實現(xiàn)自動編譯到項目里的操作
這篇文章主要介紹了idea本地jar使用maven打包本地依賴實現(xiàn)自動編譯到項目里的操作,本文通過示例代碼給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧2024-05-05關(guān)于Java 項目封裝sqlite連接池操作持久化數(shù)據(jù)的方法
這篇文章主要介紹了Java 項目封裝sqlite連接池操作持久化數(shù)據(jù)的方法,文中給大家介紹了sqlite的體系結(jié)構(gòu)及封裝java的sqlite連接池的詳細過程,需要的朋友可以參考下2021-11-11