我尝试使用 Spring Boot 连接多个 mongodb 数据库,但出现此错误

时间:2021-01-27 09:33:04

标签: spring mongodb spring-boot multiple-databases

我尝试使用 Spring boot 连接多个 mongodb 数据库,但出现此错误:“考虑在您的配置中定义一个名为‘MONGO_TEMPLATE’的 BEAN”

enter image description here

到目前为止我是如何尝试实现这一点的:

        package com.wipro.MongoConnector.Config;
        import org.springframework.boot.autoconfigure.mongo.MongoProperties;
        import org.springframework.boot.context.properties.EnableConfigurationProperties;
        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.Configuration;
        import org.springframework.context.annotation.Primary;
        import org.springframework.data.mongodb.MongoDatabaseFactory;
        ///import org.springframework.data.mongodb.MongoDbFactory; // depricated since spring 3.0
        import org.springframework.data.mongodb.core.MongoTemplate;
        import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

        import com.mongodb.MongoClient;

        import lombok.RequiredArgsConstructor;

        @Configuration
        @RequiredArgsConstructor
        @EnableConfigurationProperties(MultipleMongoProperties.class)

        public class MultipleMongoConfig{
        private final MultipleMongoProperties mongoProperties;
        public MultipleMongoConfig(MultipleMongoProperties multipleMongoProperties) {
        this.mongoProperties = multipleMongoProperties;
        }
       @Primary
       @Bean(name = PrimaryMongoConfig.MONGO_TEMPLATE)
       public MongoTemplate primaryMongoTemplate() throws Exception{
         return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary()));
       }
       @Bean(name = SecondaryMongoConfig.MONGO_TEMPLATE)
       public MongoTemplate secondaryMongoTemplate() throws Exception{
         return new MongoTemplate(secondaryFactory(this.mongoProperties.getPrimary())); 
       }
       @Primary
       @Bean
       public MongoDatabaseFactory primaryFactory(final MongoProperties mongo) throws Exception {
         return new SimpleMongoClientDatabaseFactory((com.mongodb.client.MongoClient) new 
         MongoClient(mongo.getHost(), mongo.getPort()), mongo.getDatabase());
      }
      @Bean
      public MongoDatabaseFactory secondaryFactory(final MongoProperties mongo) throws Exception {
         return new SimpleMongoClientDatabaseFactory((com.mongodb.client.MongoClient) new 
         MongoClient(mongo.getHost(), mongo.getPort()), mongo.getDatabase());
      }

    }

0 个答案:

没有答案