Spring XML MongoDB连接配置指定用户名和密码注意事项

背景:
MongoDB改成使用用户名和密码连接后 修改遗留工程 使用Spring xml 配置

MongoDB客户端版本

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

刚开始做了如下的修改

<mongo:mongo host="${mongo.host}" port="${mongo.port}" id="mongo"></mongo:mongo>
<mongo:db-factory dbname="${mongo.dbname}" mongo-ref="mongo" id="mongoDbFactory" username ="${mongo.username}" password="${mongo.password}" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>

增加了用户名和密码后 以为可以正常连接 但是始终报错

com.mongodb.MongoQueryException: Query failed with error code 13 and error message 'not authorized on test to execute command { find: "test", filter: { _id: ObjectId('5b75916f266c3a7c0345430f') }, limit: 1, singleBatch: true }' on server 127.0.0.1:27017

奇怪的是 终端中可以正常连接

➜  ~ mongo test  -u test -p 123456
rs0:PRIMARY> db
test
rs0:PRIMARY> show collections
test

于是改成直接使用Java代码连接 发现XML配置中使用的MongoDbFactory构造方法已经过期了

Spring XML MongoDB连接配置指定用户名和密码注意事项

提示

since 1.7. The credentials used should be provided by MongoClient.getCredentialsList().

于是改用了一个未过期的构造方法

MongoClient mongoClient = new MongoClient(new ServerAddress(), ImmutableList.of(MongoCredential.createCredential(username, databaseName, password.toCharArray())));
SimpleMongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, databaseName);
MongoOperations mongoOps = new MongoTemplate(mongoDbFactory);

此时能够成功连接 对应的XML配置为

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mongo="http://www.springframework.org/schema/data/mongo"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/data/mongo
        http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">

    <mongo:mongo-client host="${mongo.host}" port="${mongo.port}" id="mongoClient" credentials="${mongo.username}:${mongo.password}@${mongo.dbname}">
    </mongo:mongo-client>
    <mongo:db-factory dbname="${mongo.dbname}" mongo-ref="mongoClient" id="mongoDbFactory" />
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    </bean>

</beans>

参考文档
https://docs.spring.io/spring...

相关推荐