MongoDB保姆级指南:无缝集成SpringData框架,一篇最全面的Java接入指南!
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import java.util.Collections;
@Configuration
public class MongoConfig extends AbstractMongoClientConfiguration {
@Autowired
private MongoProperties mongoProperties;
@Override
protected String getDatabaseName() {
return mongoProperties.getDatabase();
}
@Override
public MongoClient mongoClient() {
ServerAddress serverAddress = new ServerAddress(mongoProperties.getHost(), mongoProperties.getPort());
MongoCredential credential = MongoCredential.createCredential(mongoProperties.getUsername(),
mongoProperties.getDatabase(),
mongoProperties.getPassword());
return new MongoClient(serverAddress, Collections.singletonList(credential));
}
}
这段代码演示了如何在Spring应用程序中配置MongoDB客户端。它使用自定义的MongoProperties
类来获取数据库连接的相关配置。通过继承AbstractMongoClientConfiguration
,它覆盖了getDatabaseName
方法以指定默认数据库,并实现了mongoClient()
方法来创建一个带有认证信息的MongoClient
实例。这样,Spring Data MongoDB模块就可以与MongoDB无缝集成。
评论已关闭