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>
编程是一个很严谨的活儿 : )