簡體   English   中英

使MongoClient實例成為單例

[英]make MongoClient instance as singleton

我有一個使用MongoDB作為數據庫的java-spring Web應用程序。 下面的行用於連接數據庫。

public class SpringMongoConfig {
@Bean
public MongoClient mongo() throws Exception {
    ServerAddress serverAddress = new ServerAddress(databaseUri, databasePort);
    List<MongoCredential> credentials = (databaseAuthenticationEnabled) ? Arrays.asList(
            MongoCredential.createCredential(databaseUser, authenticationDatabase, databasePassword.toCharArray()))
            : null;
    return new MongoClient(serverAddress, credentials);         
}

}

在另一個類中,我將如何獲得這個mongoClient實例?

我假設SpringMongoConfig實際上是用@Configuration注釋的,因此:

你需要找到你的another class的配置和@ImportSpringMongoConfig ,是這樣的:

 @OtherConfigOfAnotherClass
 @Import(SpringMongoConfig.class)

然后簡單地@Autowire服務中的MongoClient。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM