[英]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
的配置和@Import
的SpringMongoConfig
,是這樣的:
@OtherConfigOfAnotherClass
@Import(SpringMongoConfig.class)
然后簡單地@Autowire
服務中的MongoClient。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.