我尝试将我的 data-mongo 示例项目升级到 Spring Boot 2.6.0。有一个针对 Testcontainers 运行的测试,我还包括了嵌入式 mongo dep 用于其他测试,所以我必须排除嵌入式 mongo 的 AutoConfiguration 以确保该测试在 Docker/testcontainers 上运行。
以下配置适用于 Spring Boot 2.5.6。
@DataMongoTest
@ContextConfiguration(initializers = {MongodbContainerInitializer.class})
@EnableAutoConfiguration(exclude = EmbeddedMongoAutoConfiguration.class)
@Slf4j
@ActiveProfiles("test")
public class PostRepositoryTest {}
但是在升级到 Spring Boot 2.6.0 并运行应用程序后,我得到了这样的异常。
[ main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: o
rg.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'embeddedMongoServer' defined in class path resource [org/springframework/boot/autoconfig
ure/mongo/embedded/EmbeddedMongoAutoConfiguration.class]: Unsatisfied dependency expressed through method 'embeddedMongoServer' parameter 0; nested exception is org.springframework.bea
ns.factory.BeanCreationException: Error creating bean with name 'embeddedMongoConfiguration' defined in class path resource [org/springframework/boot/autoconfigure/mongo/embedded/Embed
dedMongoAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [de.flap
doodle.embed.mongo.config.MongodConfig]: Factory method 'embeddedMongoConfiguration' threw exception; nested exception is java.lang.IllegalStateException: Set the spring.mongodb.embedd
ed.version property or define your own MongodConfig bean to use embedded MongoDB
显然,@EnableAutoConfiguration(exclude =...)
升级到 Spring Boot 2.6.0 时不会影响测试中的上下文。
更新:暂时解决了,见下面我的回答。