使用 Java Spring 连接到 MongoDB 3.0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28958789/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Connecting to MongoDB 3.0 with Java Spring
提问by Luca Stucchi
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
我在使用 Spring 通过凭据访问 MongoDB 时遇到问题。虽然没有凭据它就像一个魅力,使用它们只是失败说
Failed to authenticate to database [yourdatabase], username = [yourusername], password = [x******z]
It must be because of new auth default that you can read about in http://docs.mongodb.org/manual/core/authentication/
这一定是因为您可以在http://docs.mongodb.org/manual/core/authentication/ 中阅读的新身份验证默认值
Changed in version 3.0: SCRAM-SHA-1 is the default mechanism for MongoDB versions beginning with the 3.0 series.
在 3.0 版更改:SCRAM-SHA-1 是 3.0 系列开始的 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 ?
问题:有人找到了一种通过凭据使用 Spring 的方法吗?spring-data-mongodb
你用哪个版本来制作这个技巧?
采纳答案by Luca Stucchi
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.
这是 MongoDB 3.0 的全新安装,不涉及升级。
I used these maven dependencies:
我使用了这些 Maven 依赖项:
<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>
having as parent
作为父母
<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());
}
And finally wherever you have access to the MongoTemplate bean you'll be able to do
最后,无论你在哪里可以访问 MongoTemplate bean,你都可以做
mongoTemplate.insert(objectToStore, collectionName);
回答by Normunds Kalnberzins
There are two of possibilities how to make Mongodb 3 work with Spring data. Both involve downgrading of authentication schema:
如何使 Mongodb 3 使用 Spring 数据有两种可能性。两者都涉及身份验证模式的降级:
start with mongodb 2.x and upgrade to 3.0; works as authentication system stays the same
if you have a new installation of mongo 3.0, you can downgrade the authentication schema before creating the users.
从mongodb 2.x开始,升级到3.0;身份验证系统保持不变
如果您新安装了 mongo 3.0,则可以在创建用户之前降级身份验证架构。
To downgrade the authentication mechanism:
要降级身份验证机制:
var schema = db.system.version.findOne({"_id" : "authSchema"})
schema.currentVersion = 3
db.system.version.save(schema)
Or you can even have mixed users, some created with version 5 (that of mongo 3) and some with version 3. Except you will be able to connect (from Spring data) only with users created using version 3.
或者,您甚至可以拥有混合用户,有些是使用版本 5(mongo 3 的)创建的,有些是使用版本 3 创建的。除了您将只能(从 Spring 数据)连接到使用版本 3 创建的用户。
You could try 3.0 + mongo 3 beta drivers: in general this combination works with "legacy code", but I did not manage to make it work with Spring Data.
您可以尝试 3.0 + mongo 3 beta 驱动程序:通常这种组合适用于“遗留代码”,但我没有设法使其适用于 Spring Data。
回答by Ali Dehghani
spring.data.mongodb.host
and spring.data.mongodb.port
are not supported if you're using the Mongo 3.0 Java driver. In such cases, spring.data.mongodb.uri
should be used to provide all of the configuration, like this:
spring.data.mongodb.host
spring.data.mongodb.port
如果您使用的是Mongo 3.0 Java 驱动程序,则不受支持。在这种情况下,spring.data.mongodb.uri
应该使用提供所有的配置,像这样:
spring.data.mongodb.uri=mongodb://user:[email protected]:12345
Just add the spring.data.mongodb.uri
to your application.yml
and you'll get the auto configured MongoDbFactory
and MongoTemplate
.
只需添加spring.data.mongodb.uri
到您的application.yml
,你就会得到自动配置MongoDbFactory
和MongoTemplate
。
回答by XLi
Here is xml version to connect MongoDB 3.0.7 with Spring (parameters are passed from a property file):
这是将 MongoDB 3.0.7 与 Spring 连接的 xml 版本(参数从属性文件传递):
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<mongo:mongo-client host="${mongo.url}" port="${mongo.port}" credentials="${mongo.user}:${mongo.pass}@${mongo.dbname}">
<mongo:client-options write-concern="NORMAL" />
</mongo:mongo-client>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongo" ref="mongo"/>
<constructor-arg name="databaseName" value="${mongo.dbname}"/>
</bean>
Then in Java, you get mongoTemplate like this:
然后在 Java 中,你会得到这样的 mongoTemplate:
@Autowired
MongoTemplate mongoTemplate;
public String mongoTest() {
DBCollection dc = mongoTemplate.getCollection("yourCollection");
logger.debug("--get collection name=" + dc.getFullName());
}
回答by manelseo
using this versions in your pom:
在你的 pom 中使用这个版本:
<!-- mongodb java driver -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.2.1</version>
</dependency>
<!-- Spring data mongodb -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.8.2.RELEASE</version>
</dependency>
And this configuration in spring:
而春天的这个配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<!-- Seeds -->
<bean id="mongoSeedListID" class="java.util.ArrayList">
<constructor-arg>
<list>
<ref bean="mongoSeedlID" />
</list>
</constructor-arg>
</bean>
<bean id="mongoSeedlID" class="com.mongodb.ServerAddress">
<constructor-arg type="java.lang.String" name="host" value="DATABASE_HOST" />
<constructor-arg type="int" name="port" value="DATABASE_PORT" />
</bean>
<!-- Credentials -->
<bean id="mongoCredentialListID" class="java.util.ArrayList">
<constructor-arg>
<list>
<ref bean="mongoCredentialID" />
</list>
</constructor-arg>
</bean>
<bean id="mongoCredentialID" class="com.mongodb.MongoCredential">
<constructor-arg name="mechanism" value = "#{T(com.mongodb.AuthenticationMechanism).SCRAM_SHA_1}" />
<constructor-arg type="java.lang.String" name="userName" value="DATABASE_USERNAME" />
<constructor-arg type="java.lang.String" name="source" value="DATABASE_SOURCE" />
<constructor-arg type="char[]" name="password" value="DB_USER_PASS" />
</bean>
<!-- MongoClient -->
<bean id="mongoClientID" class="com.mongodb.MongoClient">
<constructor-arg ref="mongoSeedListID" />
<constructor-arg ref="mongoCredentialID" />
</bean>
<!-- MongoDbFactory -->
<bean id="simpleMongoDbFactoryID" class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
<constructor-arg ref="mongoClientID" />
<constructor-arg name="databaseName" value="APP_DATABASENAME" />
</bean>
<!-- MongoTemplate -->
<bean id="mongoTemplateID" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="simpleMongoDbFactoryID" />
</bean>
<bean id="log4jInitializationID" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="org.springframework.util.Log4jConfigurer" />
<property name="targetMethod" value="initLogging" />
<property name="arguments">
<list>
<value>classpath:log4j/log4j_test.properties</value>
</list>
</property>
</bean>
</beans>
With this configuration you only have to inject the MongoTemplate:
使用此配置,您只需注入 MongoTemplate:
@Autowired
@Qualifier("mongoTemplateID")
private MongoTemplate mongoTemplate;
This should work fine =)
这应该可以正常工作 =)