【Springboot & Mongodb6.0】ERROR 18080 --- [ main] o.s.boot.SpringApplication

一、问题

本人是一名Spring小白,跟着黑马的课程学习Mongodb时出现了如下报错:

ERROR 18080 --- [           main] o.s.boot.SpringApplication               : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'commentService': Unsatisfied dependency expressed through field 'commentRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'commentRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDataAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.dao.DataAccessResourceFailureException: Timed out after 30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, servers=[{address=192.168.40.141:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: Connect timed out}}]; nested exception is com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, servers=[{address=192.168.40.141:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: Connect timed out}}]

二、定位

观察上述报错的第二行,我发现主要问题有三个:

  1. 创建Bean错误:UnsatisfiedDependencyException: Error creating bean with name 'commentService': Unsatisfied dependency expressed through field 'commentRepository';
  2. 连接数据库超时:DataAccessResourceFailureException: Timed out after 30000 ms while waiting to connect.
  3. 数据库中存在不同名字的索引:这个信息提示好像在另一行,我忘了保存了

经过问题定位,我发现之前我在userid字段上建立了名为userid_1的索引,而黑马的代码会对userid字段建立名为userid的索引,故冲突。下图是我之前建立的索引:
索引
项目中建立索引的代码如下:

//添加了一个单字段的索引
@Indexed
private String userid;//发布人ID

三、解决

删除数据库中与项目中命名冲突的索引即可:
在这里插入图片描述
之后,代码可正确执行:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45800258/article/details/128470443
今日推荐