使用Java Spring连接到MongoDB 3.0 [英] Connecting to MongoDB 3.0 with Java Spring

查看:98
本文介绍了使用Java Spring连接到MongoDB 3.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Spring访问带有凭据的MongoDB时遇到了问题。
虽然没有凭据但它就像魅力一样,使用它们只是失败说

I am having problems in using Spring to access MongoDB with credentials. While without credentials it works like a charme, using them just fails saying

    Failed to authenticate to database [yourdatabase], username = [yourusername], password = [x******z] 

必须因为您可以在 http://docs.mongodb.org/manual/core/authentication中阅读新的身份验证默认值/


在3.0版中更改:SCRAM-SHA-1是从3.0系列开始的MongoDB版本的默认机制。

Changed in version 3.0: SCRAM-SHA-1 is the default mechanism for MongoDB versions beginning with the 3.0 series.

问题:有人发现了一种使用Spring凭证的方法吗?您使用哪个版本的 spring-data-mongodb 来制作技巧?

Question: Anybody found out a way to use Spring with credentials ? Which version of spring-data-mongodb did you use to make the trick ?

推荐答案

经过大量尝试和阅读后,我找到了一种方法,使MongoDB 3.0可以使用身份验证。

After a lot of attempts and reading, I found a way to make MongoDB 3.0 work with authentication.

这是MongoDB 3.0的新安装,没有升级参与其中。

This was a new installation of MongoDB 3.0, no upgrade involved.

我使用了这些maven依赖项:

I used these maven dependencies:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.6.2.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.0.0</version>
</dependency>

作为父母

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.2.RELEASE</version>
</parent>

然后在我的配置文件中我有

Then in my Configuration file I had

/**
 * DB connection Factory
 * 
 * @return a ready to use MongoDbFactory
 */
@Bean
public MongoDbFactory mongoDbFactory() throws Exception {

    // Set credentials      
    MongoCredential credential = MongoCredential.createCredential(mongoUser, databaseName, mongoPass.toCharArray());
    ServerAddress serverAddress = new ServerAddress(mongoHost, mongoPort);

    // Mongo Client
    MongoClient mongoClient = new MongoClient(serverAddress,Arrays.asList(credential)); 

    // Mongo DB Factory
    SimpleMongoDbFactory simpleMongoDbFactory = new SimpleMongoDbFactory(
            mongoClient, databaseName);

    return simpleMongoDbFactory;
}

/**
 * Template ready to use to operate on the database
 * 
 * @return Mongo Template ready to use
 */
@Bean
public MongoTemplate mongoTemplate() throws Exception {
    return new MongoTemplate(mongoDbFactory());
}

最后,无论你有权访问MongoTemplate bean,你都可以执行

And finally wherever you have access to the MongoTemplate bean you'll be able to do

mongoTemplate.insert(objectToStore, collectionName);

这篇关于使用Java Spring连接到MongoDB 3.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆