Spring 整合Mybatis报错
警告: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘sqlSessionFactory’ defined in class path resource [spring-mybatis.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 id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://:3306/mybatisdb?useSSL=false&serverTimezone=UTC&characterEncoding=utf8"/>
<property name="username" value="Mysql"/>
<property name="password" value="XXX"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--<property name="dataSource" value="dataSource"/>错误的例子-->
<property name="configLocation" value="mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
如果不仔细看很难发现是属性的键写错了,应该是ref,自己写的快写成了value。如果最开始碰到上面的哪个错误Failed to convert property value of type 'java.lang.String' to required type 'javax.sql.DataSource' for property 'dataSource';
可能会一脸懵逼,为啥配置文件里面会有类型转换的错误,看完正确的写法可能就明白,传递的参数是javax.sql.DataSource
是需要用ref
作为键传递的一个引用对象。如果写成value
传递的一个字符串对象就会报上面的类型转化的错误。这种类型的错误可能有很多种类,但应该都是ref和value
搞混而引发的错误。以后写配置文件的时候要仔细点,IDEA的提示也会诱导你犯错。