【问题标题】:Spring Boot 2.1 duplicate reactiveMongoTemplate beanSpring Boot 2.1 复制 reactiveMongoTemplate bean
【发布时间】:2020-01-05 17:51:11
【问题描述】:

我有以下 Spring Boot @Configuration 类:

@Configuration
@EnableReactiveMongoRepositories
class MongoConfiguration : AbstractReactiveMongoConfiguration()
{
    override fun reactiveMongoClient() = MongoClients.create()

    override fun getDatabaseName() = "mydb"

    override fun customConversions(): MongoCustomConversions =
            MongoCustomConversions(listOf(ZonedDateTimeReadConverter(), ZonedDateTimeWriteConverter()))
}

应用程序无法启动,并记录此消息:

无法注册在类路径资源 [org/springframework/boot/autoconfigure/data/mongo/MongoReactiveDataAutoConfiguration.class] 中定义的 bean 'reactiveMongoTemplate'。已在类路径资源 [com/mypackage/MongoConfiguration.class] 中定义了具有该名称的 bean,并且已禁用覆盖。

这让我很困惑,因为MongoReactiveDataAutoConfiguration 中的reactiveMongoTemplate ben 方法配置了@ConditionalOnMissingBean

【问题讨论】:

    标签: spring-boot kotlin spring-data-mongodb


    【解决方案1】:

    正如安迪的回答正确指出的那样,AbstractReactiveMongoConfiguration#reactiveMongoTemplate 的返回类型与自动配置的 bean 之间存在不匹配:第一个是 ReactiveMongoOperations,而第二个是 ReactiveMongoTemplate。由于这恰好是 bean 工厂可用的唯一类型信息,@ConditionalOnMissingBean 无效。

    所以如果我简单地覆盖AbstractReactiveMongoConfiguration#reactiveMongoTemplate 来缩小返回类型,问题就消失了:

    override fun reactiveMongoTemplate(): ReactiveMongoTemplate = 
            super.reactiveMongoTemplate() as ReactiveMongoTemplate
    

    不过这是一个小技巧:当配置了任何 ReactiveMongoOperations bean(例如,存根)时,自动配置应该退出。

    因此与安迪所说的相反,我认为问题不在于AbstractReactiveMongoConfiguration,而在于MongoReactiveDataAutoConfiguration,其中reactiveMongoTemplate bean 方法应使用@ConditionalOnMissingBean(ReactiveMongoOperations.class) 进行注释。

    这可能被遗忘了,因为通常实际的 bean 将是 ReactiveMongoTemplate。但是如果没有得到适当的支持,为什么还要有ReactiveMongoOperations 接口呢?

    【讨论】:

      【解决方案2】:

      问题出在AbstractReactiveMongoConfiguration 中,您已对其进行了子分类。其reactiveMongoTemplate@Bean 方法的签名声明它返回ReactiveMongoOperations。在创建 bean 之前,这就是所有可用的类型信息,bean factory 无法知道 bean 实际上是 ReactiveMongoTemplate 实例。结果,正在寻找ReactiveMongoTemplate bean 的@ConditionaOnMissingBean 找不到一个,因此尝试定义这两个bean。这应该在 Spring Data MongoDB 中修复,以便AbstractReactiveMongoConfiguration 为其 bean 提供尽可能多的类型信息。我打开了DATAMONGO-2355

      你可以通过更多地使用 Spring Boot 的自动配置来避免这个问题。而不是子类 AbstractReactiveMongoConfiguration 你可以:

      1. 使用配置属性spring.data.mongodb.database=mydb 设置数据库。
      2. 使用自动配置的 MongoClient bean,而不是自己定义。
      3. 定义您自己的 MongoCustomConversions bean,然后将其用于支持 Boot 自动配置的 bean。

      【讨论】:

      • 我猜他们也可以在“ConditionalOnMissingBean”注释中指定“ReactiveMongoOperations”,或者作为“MongoReactiveDataAutoConfiguration”中方法的返回类型。
      • 查看我的答案以获得不同的修复。我同意使用更多的自动配置更好,并且根本原因必须在 Spring Data MongoDb 本身中修复。
      • 顺便说一句,我什至不需要自定义转换。应该在数据模型中使用Instant,因为在转换java.util.Date 并以UTC 存储在MongoDb 时,原始时区无论如何都会丢失:)
      猜你喜欢
      • 2019-04-07
      • 2019-07-16
      • 2019-04-05
      • 1970-01-01
      • 2019-05-01
      • 2021-10-28
      • 1970-01-01
      • 2019-04-18
      • 2020-06-21
      相关资源
      最近更新 更多