创建两个类型为MongoDatabaseFactory的bean时如何避免这种情况

问题描述

在某些条件下,将创建两个类型为MongoDatabaseFactory的bean:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method mongoTemplate in org.springframework.data.mongodb.config.AbstractMongoClientConfiguration required a single bean,but 2 were found:
 - mongoDatabaseFactory: defined by method 'mongoDatabaseFactory' in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryConfiguration.class]
 - mongoDbFactory: defined by method 'mongoDbFactory' in org.springframework.data.mongodb.config.AbstractMongoClientConfiguration

Action:

Consider marking one of the beans as @Primary,updating the consumer to accept multiple beans,or using @Qualifier to identify the bean that should be consumed

我想当通过AbstractMongoClientConfiguration从XML将扩展了<context:component-scan base-package="..." />的Mongo配置类添加到Spring上下文时,就会发生这种情况

@ConditionalOnMissingBean(MongoDatabaseFactory.class)
class MongoDatabaseFactoryConfiguration {

解决方法是将@Primary批注添加到扩展AbstractMongoClientConfiguration的方法中

@Override
@Primary
@Bean
public MongoDatabaseFactory mongoDbFactory() {
    return super.mongoDbFactory();
}

但是我不确定这是正确的方法,因为无论如何都会创建两个工厂。

另一种选择是禁用MongoReactiveDataAutoConfiguration

@Configuration
@EnableAutoConfiguration(exclude = MongoReactiveDataAutoConfiguration.class)
public class Application {

但这不是我的选择。

任何关于@ConditionalOnMissingBean(MongoDatabaseFactory.class)为何无法正常运行的评论,或者欢迎有关好的/干净解决方案的建议。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)