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构造方法已经过期了

clipboard.png

提示

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...

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值