springboot中設(shè)置多個(gè)MongoDB數(shù)據(jù)源

springboot中 如果配置打個(gè)數(shù)據(jù)源 默認(rèn)是讀取host port這些 沒(méi)有讀取url

spring:
  data:
    mongodb:
      username: test
      password: test
      port: 8086
      host: 127.0.0.1
      authentication-database: admin
      database: mongo_test

但是如果想配置多個(gè)數(shù)據(jù)源 需要用url的方式才能滿足需求,為了配置多個(gè)MongoDB的數(shù)據(jù)源,網(wǎng)上找了很多資料都不好用,特意記錄在這里 方便后面的兄弟姐妹使用
首先建立一個(gè)抽象的總類

@Data
public abstract class AbstractMongoConfig {
    String url;
    String database;
    public MongoDbFactory mongoDbFactory() throws Exception {
        return new SimpleMongoDbFactory(new MongoClient(new MongoClientURI(url)), database);
    }
    public abstract  MongoTemplate getMongoTemplate() throws Exception;
}

然后配置分?jǐn)?shù)據(jù)源 如

@Configuration
@ConfigurationProperties(prefix = "spring.data.mongodb.mango-account")
public class AccountConfig extends AbstractMongoConfig{
    @Override
    @Primary
    @Bean(name="accountMongoTemplate")
    public MongoTemplate getMongoTemplate() throws Exception {
        return new MongoTemplate(mongoDbFactory());
    }
}

這樣就配置成功啦.如果還沒(méi)有配置成功的同學(xué) 可以點(diǎn)一下 看看源碼 我就是這樣配的

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容