Kotlin+Spring Boot使用R2DBC连接MySQL失败求助
问题
本人来自.NET技术栈,首次尝试Kotlin开发测试。本地已安装DBeaver,可正常连接远程MySQL数据库。通过start.spring.io生成Spring Boot 3.0.0项目,配置为Gradle-Groovy、Java 17、Jar包格式,依赖Spring Web、Spring Data R2DBC和MySQL Driver。
application.properties配置如下:
spring.r2dbc.url=r2dbc:pool:mysql://192.168.1.2:3306/DBEmployee spring.r2dbc.username=root spring.r2dbc.password=password logging.level.root=DEBUG
启动应用时出现错误:
2022-12-18T10:01:16.162Z ERROR 8340 --- [ main] o.s.boot.SpringApplication : Application run failed ... Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [io.r2dbc.spi.ConnectionFactory]: Factory method 'connectionFactory' threw exception with message: Unable to create a ConnectionFactory for 'ConnectionFactoryOptions{options={database=DBEmployee, host=192.168.1.2, driver=mysql, password=REDACTED, protocol=, port=3306, user=root}}'. Available drivers: [ pool ] at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:171) ~[spring-beans-6.0.2.jar:6.0.2] at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:648) ~[spring-beans-6.0.2.jar:6.0.2] ... 19 common frames omitted Caused by: java.lang.IllegalStateException: Unable to create a ConnectionFactory for 'ConnectionFactoryOptions{options={database=DBEmployee, host=192.168.1.2, driver=mysql, password=REDACTED, protocol=, port=3306, user=root}}'. Available drivers: [ pool ] at io.r2dbc.spi.ConnectionFactories.get(ConnectionFactories.java:143) ~[r2dbc-spi-1.0.0.RELEASE.jar:na]
解决方案
错误核心是项目缺少MySQL的R2DBC专用驱动依赖:你当前添加的MySQL Driver是JDBC驱动,而R2DBC需要对应的响应式驱动来创建连接工厂。
在Gradle-Groovy的build.gradle中添加以下依赖:
// Spring Boot 3.x推荐使用这个迁移后的驱动groupId runtimeOnly 'io.asyncer:r2dbc-mysql:1.1.2'
如果偏好原驱动groupId,可使用兼容版本:
runtimeOnly 'io.r2dbc:r2dbc-mysql:1.0.2.RELEASE'
添加完成后同步Gradle依赖,重启项目即可解决该问题。
内容的提问来源于stack exchange,提问作者Antônio Godinho
相关产品推荐
相关产品推荐

