I tried to connect multiple mongodb database using Spring boot, but I am getting this error: "Consider defining a BEAN named 'MONGO_TEMPLATE' in your configuration"
How I tried to implement this so far:
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());
}
}
question from:
https://stackoverflow.com/questions/65916343/i-tried-to-connect-multiple-mongodb-database-using-spring-boot-but-i-am-getting 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…