Spring中Bean的property,ref引發的小問題


今天在配置Spring的配置文件applicationContext.xml文件時,一時順手把配置Mybatis的Bean寫成了這個樣子
這里寫圖片描述
結果在測試mapper的時候拋出了這個異常:

警告 [RMI TCP Connection(3)-127.0.0.1] org.springframework.web.context.support.XmlWebApplicationContext.refresh Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in class path resource [applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.String' to required type 'javax.sql.DataSource' for property 'dataSource'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'javax.sql.DataSource' for property 'dataSource': no matching editors or conversion strategy found

簡單看了下發現Bean的一個property”dataSource”出現了問題,Spring表示並不知道你想要干啥?
看到這一下子就有點懵,心想我不是給你賦了引用類型”pooledDataSource”了么?怎么還…
忽然我就發現我把ref寫成了value.
我們知道value是用來賦值一般類型的,在這里Spring就會把我們的”pooledDataSource”當成一個字符串來處理,而不會去找我們配置的pooledDataSource這個數據源bean.
ref是賦值引用類型的,Spring就會去加載對應的bean,完成sqlSessionFactory這個bean的屬相注入.
正確的寫法應該是

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定mybatis全局配置文件的位置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="dataSource" ref="pooledDataSource"/>
        <!-- 指定mybatis,mapper文件的位置 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
</bean>

編程是一個很嚴謹的活兒 : )


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM