配置文件
## 第一个配置
spring.data.mongodb.first.database=idisback
spring.data.mongodb.first.uri=mongodb://yingfuroot:yingfurootpwd@192.168.104.40:27017/admin
spring.data.mongodb.firs.username=yingfuroot
spring.data.mongodb.firs.password=yingfurootpwd
spring.data.mongodb.firs.authenticationDatabase=admin
## 第二个配置
spring.data.mongodb.second.database=handle
spring.data.mongodb.second.uri=192.168.104.39:27017
@Configuration
public class MultipleMongoProperties {
@Bean(name = "firstMongoProperties")
@Primary
@ConfigurationProperties(prefix = "spring.data.mongodb.first")
public MongoProperties firstMongoProperties() {
System.out.println("-------------------- statisMongoProperties init ---------------------");
return new MongoProperties();
}
@Bean(name = "secondMongoProperties")
@ConfigurationProperties(prefix = "spring.data.mongodb.second")
public MongoProperties secondMongoProperties() {
System.out.println("-------------------- listMongoProperties init ---------------------");
return new MongoProperties();
}
}
@Configuration
@EnableMongoRepositories(basePackages = "cn.teleinfo.snms.data.repository.first", mongoTemplateRef = "firstMongo")
public class FirstMongoTemplate {
@Autowired
@Qualifier("firstMongoProperties")
private MongoProperties mongoProperties;
@Primary
@Bean(name = "firstMongo")
public MongoTemplate firstMongoTemplate() throws Exception {
return new MongoTemplate(firstFactory(this.mongoProperties));
}
@Bean
@Primary
public MongoDbFactory firstFactory(MongoProperties mongoProperties) throws Exception {
return new SimpleMongoDbFactory(new MongoClient(new MongoClientURI(mongoProperties.getUri())), mongoProperties.getDatabase());
}
}
@Configuration
@EnableMongoRepositories(basePackages = "cn.teleinfo.snms.data.repository.second", mongoTemplateRef = "secondMongo")
public class SecondMongoTemplate {
@Autowired
@Qualifier("secondMongoProperties")
private MongoProperties mongoProperties;
@Bean(name = "secondMongo")
public MongoTemplate secondTemplate() throws Exception {
return new MongoTemplate(secondFactory(this.mongoProperties));
}
@Bean
public MongoDbFactory secondFactory(MongoProperties mongoProperties) throws Exception {
ServerAddress serverAdress = new ServerAddress(mongoProperties.getUri());
return new SimpleMongoDbFactory(new MongoClient(serverAdress), mongoProperties.getDatabase());
}
}
来源:CSDN
作者:TBC_博客
链接:https://blog.csdn.net/sinat_31908303/article/details/103855786