我尝试使用spring boot连接多个mongodb数据库,但遇到了以下错误:“请考虑在配置中定义一个名为'mongo\u template'的bean”
到目前为止我是如何实现这一点的:
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());
}
}
暂无答案!
目前还没有任何答案,快来回答吧!